Multimedia End-to-End
How Android plays a file or stream and how it records one: control decisions (extractor, codec config, route, DRM license) versus the media plane (PCM, YUV, compressed access units), then the hop-by-hop path through ExoPlayer or NuPlayer, MediaCodec, AudioFlinger and SurfaceFlinger. This is the dedicated walk that Trace a Path Through the Android Stack only maps in An audio path.
- Control plane configures the pipeline (extractor, codec format, AudioPolicy route, DRM license). Media plane is the buffers. A/V sync is a third concern, not a side effect of either plane.
- App APIs: ExoPlayer / Media3 (preferred),
MediaPlayer(NuPlayer),AudioTrack/ AAudio / Oboe,MediaRecorder. Session and focus sit above the mixer. MediaCodecis the codec API. Codec2 (C2) is the preferred implementation on AOSP 13–15; OMX is the legacy path. Hardware VPU/DSP first, software C2 components as fallback.- Audio: track → AudioFlinger thread (FastMixer, deep buffer, offload, MMAP) → AudioPolicy device → Audio HAL → ALSA/DSP/codec → speaker, USB or Bluetooth A2DP/HFP. Full BT stack: Bluetooth.
- Video decode lands on a Surface (BufferQueue / BLAST) or ImageReader. Camera sensor/ISP is Camera; this page only takes a camera video Surface as an encoder source.
- Record: mic or camera Surface → encoder →
MediaMuxer→ MP4. DRM (Widevine L1/L3) wraps decrypt + a secure path, not a different codec API. - "No sound" versus "no video" is a bisect: audio dump first, then codec/extractor, then Surface/vsync. Compressed offload is a music power win; VoIP cannot use that same path.
Two planes: control vs media (and sync)
Playback and record are not one conversation. Interviewers use the split as a filter. If you start "play an MP4" with PCM sample rates and never name the extractor or the AudioPolicy route, or you start with AudioFocus and never mention access units, you have mixed the planes. A/V sync is a third concern: it is not "control" and it is not "a buffer type".
Control plane (build the pipeline)
- Container: extractor picks tracks, MIME, duration, seek map, crypto scheme.
- Codec config: CSD (SPS/PPS/VPS, AudioSpecificConfig), bitrate, profile, colour format, operating rate.
- Route: AudioPolicy strategy + devices (speaker, USB, A2DP, BLE, telephony).
- Focus / session: who may play, who ducks, MediaSession metadata and transport.
- DRM: provisioning, license request/response,
MediaCryptobound to a codec session. - Result: a running graph of components and a chosen output device. No samples have to have moved yet.
Media plane (move the samples)
- Compressed access units (NAL, AAC frame, Opus packet) from extractor or network.
- Decoded PCM (audio) or YUV / RGB (video) in GraphicBuffer / AHB / byte buffers.
- Encoded access units toward a muxer or a network sender.
- HAL streams: Audio HAL output/input, codec HAL work items, BufferQueue slots.
- Secure variants of the same buffers when L1 DRM or a secure codec is in use.
Sync is not a plane
Presentation timestamps, the audio HAL clock (or a tunneled display clock), vsync, and "hold this video frame until PTS". Control configured the clocks; media carries the PTS on each buffer. The algorithm that waits or drops sits beside both.
Why interviews mix them
A license failure is control. A green screen with audio is media (or the video renderer). Lips that lead the voice by 80 ms is sync. Name the plane before you name the dump.
Record is the same split
Control: encoder format, GOP, muxer track add, camera session. Media: PCM from AudioFlinger, YUV from a camera Surface. Sync: audio and video track timestamps in the MP4.
A cinema: booking the screen, hiring the projectionist and unlocking the film can (control) versus the actual reels running through the gate (media) versus the usher who holds the curtain until the soundtrack and picture line up (sync). The ticket office never touches a frame. The reel never negotiates a license. See the map on Trace a Path Through the Android Stack; this page is the walk.
CONTROL (once per prepare / format change) MEDIA (every access unit / PCM period)
App prepare / ExoPlayer prepare extractor.read() / queueInputBuffer
| |
Extractor + track select + CSD compressed AU (or PCM / YUV)
| |
MediaCodec.configure + start C2/OMX work → VPU / DSP / SW
| |
AudioPolicy + focus + MediaSession AudioFlinger mix / BufferQueue slot
| |
MediaDrm.openSession + license Crypto.decrypt (if needed) then render
v v
"pipeline is usable" samples at speaker / display / file
The multimedia layer cake
Same five layers as every other Android flow: app, framework / system services, native daemons and HALs, kernel, hardware. Media adds a process split so a crashing codec does not take the mixer with it. Keep the verbs straight: the app owns the player object; MediaSession and AudioFocus arbitrate; NuPlayer or ExoPlayer drives codecs; MediaCodec is the codec API; the HAL and VPU/DSP do the pixels and samples.
App process
ExoPlayer / Media3 | MediaPlayer | AudioTrack / AAudio / Oboe | MediaRecorder
MediaSession client + AudioManager focus
| Binder
Framework / native services
MediaSessionService AudioPolicyService + AudioFlinger (audioserver)
MediaPlayerService/NuPlayer (mediaserver) — or ExoPlayer stays in-app
media.extractor media.codec / vendor C2 / media.swcodec
drmserver mediametrics
| Binder / HIDL / AIDL HAL
Vendor HAL processes
codec HAL (C2 IComponentStore, legacy OMX) Audio HAL (AIDL IAudio; HIDL older)
|
Hardware
VPU / DSP / secure video path speaker, USB, BT controller
|
Display path (video only)
BufferQueue / BLAST → SurfaceFlinger → HWC → panel
(or tunneled decoder → display, bypassing SF composition)
| Layer | What lives here | Interview note |
|---|---|---|
| App | ExoPlayer / Media3, MediaPlayer, AudioTrack, AAudio, Oboe, MediaRecorder, CameraX video Surface | ExoPlayer is in the app process. MediaPlayer is a Binder stub to NuPlayer. |
| Session / focus | MediaSession, MediaSessionService, AudioManager focus, volume UI | Does not move samples. A focus loss can pause the control plane. |
| Player engine | NuPlayer inside mediaserver, or ExoPlayer renderers in-app | Both end at MediaCodec + AudioTrack (or offload / tunneled variants). |
| Codec API | MediaCodec → C2 (preferred) or OMX (legacy) | Same Java object either way. Dump the component name. |
| HAL + silicon | codec HAL, Audio HAL, VPU, audio DSP, codec IC | Secure codecs keep buffers in the TEE / protected gralloc. |
| Render | AudioFlinger threads, or BufferQueue / BLAST → SurfaceFlinger | Audio and video split here. Sync joins them by timestamp. |
Who talks to whom over Binder
App to framework is Binder; framework to vendor is stable AIDL or leftover HIDL. Codec work items and audio periods are not one Binder call per sample — they ride shared buffers, FMQ-style queues (C2), or AudioFlinger's shared-memory tracks. Binder is for configure, start, route, focus and death. See Binder & AIDL.
- App → MediaCodec / MediaPlayer / AudioFlinger Java APIs are Binder to
media.codec,mediaserveroraudioserver. - MediaCodec → C2 store / OMX The codec process binds the vendor
IComponentStore(AIDL) or the OMX HAL. - AudioFlinger → Audio HAL Output and input streams; AIDL
IAudioon current devices, HIDL on older ones — same story as the audio-path map. - Player → SurfaceFlinger Not a media Binder hop. The decoder is a BufferQueue producer; SurfaceFlinger consumes. BLAST is the usual Android 10+ queue.
A restaurant: the diner (app) orders; the maître d' (focus / session) decides who gets a table; the kitchen ticket (codec config) never tastes like food; the line cooks (C2/VPU, AudioFlinger) plate samples; the pass (SurfaceFlinger / speaker) is where guests actually see and hear the meal. ExoPlayer is a chef who cooks in the diner's private kitchen. NuPlayer is the hotel kitchen down the hall, reached by a waiter (Binder).
OMX. component names. Do not claim OMX is gone; some vendors still ship it for a codec or two.Playback: local file, HTTP and DASH
Every playback graph is extractor → decoder → renderer. The source (file fd, HTTP progressive, HLS, DASH) changes the extractor and the buffering policy, not the codec HAL. Adaptive streaming adds a control-plane loop (manifest, track select, rebuffer) around the same media plane.
A jukebox: the extractor is the person who finds the right disc and track; the decoder is the needle and amp; the renderer is the speaker and the light show. HTTP/DASH is a jukebox that phones the warehouse for the next disc when the current one is running low. The needle does not know whether the disc came from the cabinet or the warehouse.
What the extractor actually does
MediaExtractor (and ExoPlayer's extractors) parse a container: MP4/fMP4, WebM, Ogg, MPEG-TS, AAC ADTS, and so on. They do not decode. They expose tracks, MIME types, CSD buffers, seek tables, and a readSampleData that returns one access unit plus PTS/DTS and optional crypto info. On AOSP the extractor often runs in the media.extractor process so a hostile file cannot own the app (NuPlayer path). ExoPlayer typically parses in-process with its own extractors; it can still use the framework extractor for some types.
| Source | Control extras | Media extras |
|---|---|---|
| Local file / content URI / fd | One-shot prepare; seek via index or CTT | Pull access units from the container |
| HTTP progressive | Content-Length or chunked; rebuffer on stall | Same extractor once enough bytes exist |
| HLS | Playlist refresh, variant switch, discontinuity | MPEG-TS or fMP4 segments as access units |
| DASH | MPD, period/adaptation set, CENC PSSH | fMP4 fragments; often Widevine |
Audio-only hop list
App ExoPlayer / MediaPlayer.setDataSource → extractor (MIME audio/mp4a-latm, audio/mpeg, audio/opus, …) → optional MediaDrm / MediaCrypto if the track is encrypted → MediaCodec audio decoder (C2, else OMX, else c2.android.* software) → PCM 16-bit or float (or: compressed offload skips this decode on AP) → AudioTrack / AAudio (usage MEDIA, content MUSIC) → AudioFlinger thread (deep buffer or OFFLOAD; FastMixer if low-latency) → AudioPolicyService device (speaker / USB / A2DP / BLE) → Audio HAL → ALSA or DSP / codec → transducer [offload fork] compressed AU → Audio HAL offload → DSP decode → DAC
A/V hop list
Same extractor, two tracks Audio (as above) → AudioTrack → AudioFlinger → HAL clock (master) Video → MediaCodec video decoder → output Surface (app SurfaceView / TextureView / Compose) → BufferQueue / BLASTBufferQueue → SurfaceFlinger latch on vsync → HWC / GPU → panel Sync video renderer holds or drops frames so PTS ≈ audio timestamp + latency tunneled path: decoder + audio HAL share a hardware clock; SF is bypassed
- Prepare Data source opens; extractor reports tracks. Player picks one audio and one video (plus optional text).
- Configure codecs CSD queued as codec config buffers. Video codec gets a Surface. Audio codec gets PCM format or an offload flag.
- Start Input buffers fill from the extractor; output callbacks fire. AudioTrack starts; first video frame may wait for a keyframe + sync.
- Steady state Access units in, rendered buffers out. Adaptive logic may switch a rendition (new extractor + often a codec flush / reconfig).
- Seek Control: flush codecs, extractor seek to a sync sample. Media: discarded GOPs. Sync: clocks reset.
Audio path: track to transducer
This is the dedicated expansion of An audio path: app to speaker (and back). The map still holds: app track → AudioFlinger in audioserver → AudioPolicyService device → Audio HAL (AIDL IAudio, HIDL on older devices) → ALSA or vendor DSP/codec → speaker, headset or Bluetooth. Capture is the reverse: mic or BT SCO/HFP → codec/DSP → HAL → AudioFlinger → AudioRecord. What this section adds is threads, focus, ducking, volume strategies, and why the offload fork exists.
Playback:
App AudioTrack / MediaPlayer / ExoPlayer / AAudio / Oboe
──▶ AudioFlinger (audioserver) mixes or hands off a track
FastMixer | deep-buffer Mixer | OFFLOAD | MMAP | DIRECT
──▶ AudioPolicyService picks the device (speaker, earpiece, A2DP, USB, telephony)
──▶ Audio HAL (AIDL IAudio; HIDL on older devices)
──▶ kernel ALSA or vendor DSP / codec ──▶ speaker, headset, or Bluetooth
Capture (the reverse): mic / BT SCO ──▶ codec / DSP ──▶ Audio HAL ──▶ AudioFlinger ──▶ AudioRecord
Offload paths (AP can sleep):
compressed offload ──▶ DSP decodes MP3/AAC during music
AAudio MMAP ──▶ shared-memory, low-latency, less wakeups
hotword / ACD ──▶ always-on DSP; AP wakes only on a trigger
AudioFlinger is a mixing desk. Each app plugs in a channel (a track); the desk (policy) decides whether the output is the house speakers, a headset or a Bluetooth radio, and whether a junior engineer (the AP) must sit there mixing every sample or a hardware rack (the DSP) can play a finished tape unattended. In the real system a deep-buffer or compressed-offload track lets the AP suspend between callbacks; a fast or MMAP track keeps latency low for games and VoIP at a higher power cost. Same desk, same analogy as the map page — the rest of this section is the channel strip.
How a track is created
- App writes attributes
AudioAttributes(usageUSAGE_MEDIA,USAGE_VOICE_COMMUNICATION,USAGE_ALARM, …) and a format (PCM, or compressed for offload). AAudio/Oboe set performance mode and sharing mode instead of a Java stream type. - AudioFlinger opens a track Shared memory for PCM; a compressed track for offload. The client writes frames; the server thread reads them.
- Policy picks a device and a thread type Strategy from the usage, current devices, forced routing (call, dock), and whether offload / MMAP / fast is allowed.
- HAL stream Playback thread calls into the Audio HAL output. The HAL talks ALSA PCM, a vendor DSP RPC, USB audio, or the BT audio HAL.
AudioFlinger thread types
| Thread | Job | When you see it |
|---|---|---|
| FastMixer | Low-period mix (a few ms). AP stays busy. Submix of eligible fast tracks. | Games, some UI, anything that requested fast / low latency and was accepted. |
| Deep buffer (Mixer) | Larger periods, better power. Normal music / movie PCM after decode. | Default MEDIA PCM when offload is not used. |
| OFFLOAD | Compressed access units to the HAL; DSP decodes. Little AP mix. | Music when the HAL advertises the codec and policy allows it. |
| MMAP | Shared-memory burst with the HAL. AAudio exclusive/low-latency path. | VoIP, instruments, pro-audio when the board supports it. |
| DIRECT | No software mix; exclusive or passthrough (HDMI, compressed passthrough). | Rare on phones; more on dock / TV outputs. |
A track that requested fast and was rejected silently joins the deep mixer — classic "I asked for 5 ms and dumpsys shows 20 ms." Always read the thread type in dumpsys media.audio_flinger, not the app's hope.
AudioPolicy: devices, strategies, volume, ducking
AudioPolicyService does not mix. It answers: which device, which strategy, which volume curve, who is ducked, whether a call takes the voice path. Configuration comes from audio_policy_configuration.xml (and engine AIDL on current releases) plus runtime device connection callbacks.
| Idea | Examples | Effect |
|---|---|---|
| Strategy | MEDIA, PHONE, SONIFICATION, ACCESSIBILITY, ENFORCED_AUDIBLE | Picks a device set. Alarms can ignore a silent media volume. |
| Device | SPEAKER, EARPIECE, WIRED_HEADSET, USB_DEVICE, BLUETOOTH_A2DP, BLE_HEADSET, TELEPHONY_TX | HAL output. A2DP/HFP is the hop; the BT stack is Bluetooth. |
| Stream / volume group | MUSIC, VOICE_CALL, RING, ALARM, NOTIFICATION, ACCESSIBILITY | Which volume slider applies. Groups collapsed on modern UI still map here. |
| Focus | GAIN, LOSS, LOSS_TRANSIENT, LOSS_TRANSIENT_CAN_DUCK | Apps should pause or duck. Policy may also duck the losing track in the mixer. |
| Ducking | Nav prompt over music; notification over MEDIA | Volume multiply on the ducked strategy, not a second decode. |
Telephony routing is special: during a call, POLICY sends voice to EARPIECE / wired / BT HFP / LE and may mute MEDIA or park it. That is still AudioPolicy plus the telephony audio HAL path — not a second AudioFlinger. IMS RTP itself is IMS; this page stops at "voice usage hit the voice strategy."
AAudio and Oboe
AAudio is the NDK API. Oboe is a C++ wrapper that uses AAudio and falls back to OpenSL ES on old devices. On AOSP 13–15, prefer "AAudio, Oboe as the portable wrapper." MMAP is a path AAudio can take, not a second API. Sharing mode EXCLUSIVE plus PERFORMANCE_MODE_LOW_LATENCY is how you ask; the server may still give you a shared mixer thread.
Bluetooth as a device hop
Policy can select DEVICE_OUT_BLUETOOTH_A2DP (music), HFP/SCO (call / some voice), or LE Audio. AudioFlinger then talks to the BT audio HAL; the ACL, A2DP codec negotiation and HFP AT commands live on Bluetooth. Interview sentence: "A2DP/HFP is the AudioPolicy device; I will not pretend I walked AVDTP unless you want the BT page."
adb shell dumpsys media.audio_flinger # tracks, threads, HAL streams, standby
adb shell dumpsys media.audio_policy # devices, volumes, focus, strategies
adb shell dumpsys audio # combined view on recent releases
adb shell dumpsys media_session # sessions, priority, metadata
dumpsys media.audio_flinger (thread type, standby) and power rails, not just the media app's process CPU. Same tip as the map page; the dump is how you prove it. See Power and thermal.Video path: decode to pixels
A video decoder's job is to turn compressed access units into frames that a consumer already owns. The consumer is usually a Surface (display or encoder), sometimes an ImageReader (CPU). You do not "get a Bitmap every frame" on the hardware path.
The decoder is a darkroom that prints onto paper the gallery already hung (the Surface's GraphicBuffers). Vsync is the hour when the gallery rotates the hanging. Tunneling is a private chute from the darkroom to the street window that skips the gallery staff (SurfaceFlinger composition). ImageReader is asking the darkroom for a print you can take home and scan (CPU).
MediaCodec video decoder (C2 / OMX)
output to Surface
|
BufferQueue / BLASTBufferQueue (producer = codec, consumer = SF or encoder)
|
release fence: GPU / decoder done
|
SurfaceFlinger latch on vsync
|
HWC device composition or GPU client composition
|
display
Alternate consumers
ImageReader → Image (YUV / JPEG) → app CPU / ML
PersistentInputSurface of a second MediaCodec → transcode / record
Encoder Surface from Camera → see record-encode; ISP details on camera.html
Surface, BufferQueue, BLAST
A Surface is a producer handle onto a BufferQueue. The codec dequeues a free GraphicBuffer, writes a decoded frame (often via the VPU into gralloc), and queues it with a fence. SurfaceFlinger (or BLAST's consumer side) waits the fence, latches on vsync, and composites. BLASTBufferQueue is the usual Android 10+ path: same producer-consumer idea, cheaper SurfaceFlinger transactions. Do not say BufferQueue "went away."
Fences are the sync objects between VPU, GPU and display. If you block the app thread waiting for a decoded Bitmap, you have left the hardware path. Kernel fence and ION/gralloc details: Linux Kernel & BSP.
Vsync and why dropped frames are not "a slow decoder" by default
The display emits vsync (16.6 ms at 60 Hz, 11.1 at 90, 8.3 at 120). SurfaceFlinger latches the newest buffer per layer. If the decoder is late, SF shows the previous frame — a freeze, not a tear (tearing is a fence/HWC bug). Jank on the UI thread is a different path (Choreographer, RenderThread) than media decode jank. A 24 fps movie on a 60 Hz panel is 3:2 pulldown / repeat, not a bug.
Tunneling versus non-tunnel
| Non-tunnel (phones, default) | Tunneled playback | |
|---|---|---|
| Path | Decoder → Surface → SurfaceFlinger → HWC | Decoder writes toward the display; SF composition skipped for that layer |
| Clock | App / NuPlayer / ExoPlayer matches video PTS to audio timestamps | Hardware AV sync; audio HAL or display clock is master |
| Where | Almost all phone/tablet app video | Android TV / some HDMI / vendor low-latency paths; FEATURE_TunneledPlayback |
| Debug | SF dumps, vsync, codec output FPS | If tunnel fails, players fall back to non-tunnel — look for the feature and HAL support |
MediaCodec async callbacks
The recommended app API is asynchronous: MediaCodec.setCallback. The codec process posts:
onInputBufferAvailable— fill with an access unit (or CSD / EOS).onOutputBufferAvailable— render to Surface (releaseOutputBuffer(..., true)or with a timestamp) or copy if using Image/byte buffers.onOutputFormatChanged— mid-stream resolution / colour change; recreate views if needed.onError— fatal or recoverable; a recoverable error is often a codec reset, not a new player.
The older poll loop (dequeueInputBuffer / dequeueOutputBuffer) still exists. Interview preference: describe async, mention sync as the legacy style. Never busy-wait on the UI thread.
Record and encode: mic or Surface to MP4
Record is playback with the arrows reversed and a muxer at the end. Control: encoder format, bitrate, GOP, colour, muxer tracks. Media: PCM from AudioFlinger and YUV from a Surface (camera or GL). Camera sensor, 3A and ISP stay on Camera — here the camera is only a producer of a video Surface into the encoder.
Audio
mic / BT SCO → Audio HAL → AudioFlinger RecordThread → AudioRecord
→ MediaCodec audio encoder (AAC / AMR / Opus) → compressed AU
Video
Camera HAL3 video stream → Surface → MediaCodec video encoder
(or GL / VirtualDisplay / ImageWriter into the same Surface)
→ compressed AU (AVC / HEVC / VP8 / VP9 / AV1 as configured)
Mux
MediaMuxer.addTrack (audio) + addTrack (video)
writeSampleData with PTS
MPEG-4 / WebM / 3GPP → fd or path
A field recorder plus a camera assistant handing film magazines into one suitcase. The mic pack (AudioRecord) and the camera magazine (Surface) are different crews. The suitcase (MediaMuxer) only accepts labelled reels (tracks with a format) and stamps the time (PTS). If the suitcase is opened before both crews started, you get a file with one track. If timestamps disagree, the editor (player) thinks the clapboard never hit.
APIs that wrap the same hops
| API | Who drives the hops | Use |
|---|---|---|
MediaRecorder | Framework: audio source + camera/Surface + muxer | Simple MP4. Less control of GOP and bitrate mode. |
MediaCodec + MediaMuxer | App (or CameraX video capture) | Interview default. Full format control. |
CameraX VideoCapture | Jetpack on top of Camera2 + encoder | Still the same encoder + muxer underneath. |
Bitrate, GOP, colour
- Bitrate
KEY_BIT_RATEplusKEY_BITRATE_MODE(CQ / VBR / CBR). CBR for predictable files and some broadcast; VBR for quality at a size budget. Too low a rate at 4K is blocky; too high is a thermal/VPU problem, not a muxer problem. See power. - GOP I (sync), P, optional B.
KEY_I_FRAME_INTERVAL(seconds) andKEY_INTRA_REFRESH/ sync-frame requests. A 1–2 s GOP is typical for phone video; short GOP helps seek and damage recovery, costs bitrate. B-frames need a reordering delay — bad for ultra-low-latency conferencing. - Colour Prefer
COLOR_FormatYUV420Flexiblewhen the app touches YUV. Surface input usesCOLOR_FormatSurfaceand never sees planes. Flexible 420 is the portable layout; semi-planar NV12-style is what many VPUs actually write. Do not hard-codeCOLOR_FormatYUV420Planarand then blame the vendor whengetOutputImagefails.
Encoder Surface from camera
Camera2 / CameraX configure a video stream whose target is MediaCodec.createInputSurface() or a persistent input Surface. The ISP writes YUV into that queue; the encoder consumes it. There is no JPEG in the middle and no app memcpy on the happy path. Preview is a second stream to SurfaceFlinger. Still capture is a third (ImageReader). Do not collapse those three. ISP, 3A, and HAL3 requests: Camera End-to-End.
INFO_OUTPUT_FORMAT_CHANGED and you have addTrack for each. Writing video samples before muxer.start() throws; adding a track after start throws. This is the usual "first frame crash" in take-home recorder code.COLOR_FormatYUV420Flexible. Stop before Bayer/ISP unless they switch to the camera page.Codec HAL: C2 preferred, OMX legacy
MediaCodec is the stable app/framework API. Under it, AOSP 13–15 prefers Codec2 (C2). OMX (OpenMAX IL via the OMX HAL) is the legacy path still present for some vendor components. Software codecs are C2 components in media.swcodec (c2.android.avc.decoder and friends), not "Java decode."
Codec2 (C2)
- Work items:
C2Workwith input/outputC2FrameData, fences, and config. - Store: AIDL
IComponentStorein a vendor process; framework queries names and traits. - Allocators: gralloc / AHB / linear; secure allocators for L1.
- Names:
c2.android.*software,c2.<vendor>.*hardware. - Preferred on AOSP 10+; default story for 13–15.
OMX (legacy)
- States: Loaded → Idle → Executing; buffer headers; ports.
- HAL:
android.hardware.media.omx/IOmxnodes. - Names:
OMX.google.*software,OMX.<vendor>.*hardware. - Still appears on dumps when a vendor did not finish the C2 port.
- Do not start a 13–15 answer with OMX unless the dump says so.
App MediaCodec.configure / queue
| Binder
media.codec (or vendor codec process)
| AIDL IComponentStore / IComponent
c2.<vendor>.avc.decoder ──▶ VPU (hardware)
|
fallback
c2.android.avc.decoder ──▶ media.swcodec CPU
legacy fork
OMX.<vendor>.xxx ──▶ OMX HAL ──▶ same VPU
MediaCodec is the order form every café accepts. C2 is the modern espresso machine; OMX is the vintage lever machine still in the corner. Software C2 is instant coffee when the machine is booked or broken. The customer never orders "pull a C2Work." They order a cappuccino (video/avc decode to a Surface).
Vendor process and isolation
Hardware codecs run in a vendor process (codec HAL / C2 service) so a VPU firmware crash is not system_server. Software codecs run in media.swcodec with a tighter sandbox. SELinux and a crash dump of media.codec versus the app PID tell you which side died. Treble/VINTF lists the codec HAL just like audio and camera; see frameworks.
Hardware versus software fallback
Framework codec selection prefers hardware (alias + rank). Fallback to c2.android.* when: no component advertised for that MIME/profile (10-bit HEVC, AV1 on an old VPU), secure is required but only a non-secure component exists, or the hardware instance is exhausted (too many simultaneous 4K sessions). Software decode at 4K is a thermal and jank story, not a silent success. Selection is control-plane; the media plane just sees a component name in the dump.
Secure codecs
A secure decoder (Widevine L1, some enterprise paths) allocates protected GraphicBuffers. The app and even SurfaceFlinger may not map the pixels. Output goes to a protected composition path or a trusted display. You cannot ImageReader L1 video and screenshot it. OMX used protected gralloc usage bits; C2 uses a secure allocator. Same idea. No vendor key material belongs in an interview — see DRM.
adb shell dumpsys media.codec # components, instances, C2 vs OMX
adb shell lshal | grep -i -e c2 -e omx # which HAL is registered
adb logcat -s MediaCodec CCodec C2 # configure, flush, error
c2.android.* as fallback. Name secure allocators without inventing firmware IOCTLs.DRM: MediaDrm, Crypto, Widevine levels
DRM is control-plane license plus a media-plane decrypt that may stay in a secure path. It is not a different player. ExoPlayer and NuPlayer both bind MediaDrm + MediaCrypto to a MediaCodec session. This section stays conceptual: no keybox layout, no vendor provisioning secrets, no circumvention.
App / player MediaDrm.openSession getKeyRequest ──HTTP──▶ license server ──▶ provideKeyResponse MediaCrypto(session) bound to MediaCodec.configure(..., crypto, …) Media plane extractor yields encrypted AU + subsample crypto info codec / TEE decrypts into secure or clear buffers L1: pixels stay on the secure path to the display L3: software decrypt; buffers are ordinary (weaker)
A locked film can. The ticket office (license server) sends a night's permission (license) after the theatre proves who it is (provisioning / attestation). The projectionist (Crypto + secure decoder) unlocks each reel in a locked booth (TEE). L1 never lets the film walk out of the booth into the lobby (app memory). L3 unlocks it at the concession stand — convenient, easier to steal. You do not need to know how the lock pins are cut.
Objects
| Object | Role |
|---|---|
MediaDrm | Session, provisioning, key request/response, secure-stop / renewal as the scheme requires. |
MediaCrypto | Held by the codec; decrypts samples (or hands them to a secure decoder). |
| PSSH / scheme data | In the container or DASH MPD; tells the player which system UUID and init data to use. |
| License server | App or a DRM plugin talks HTTP. Android does not embed the studio's server. |
| drmserver / HAL | Framework daemon plus vendor DRM HAL. Binder from the app to that stack. |
Widevine security levels (conceptual)
- L1 Device has a trusted execution environment and a secure video path. Highest commercial tier. Screenshots of the video layer should fail. Needs a secure decoder component.
- L3 Software implementation. Widely available, limited resolution / robustness by studio policy. Useful for bring-up and for devices without a TEE path.
- L2 Historical / uncommon middle: decrypt in TEE, decode outside. Rare in phone interviews; do not dwell.
Other schemes exist (ClearKey for tests, vendor/enterprise systems). In a general Android interview, name Widevine levels plus "ClearKey for CTS / unencrypted-equivalent tests." Do not claim a factory key hierarchy.
Secure path
L1 success is more than "decrypt worked." The decoded buffers must remain protected through composition. A player that decodes L1 then tries to blit through an ordinary TextureView / ImageReader will fail or black-frame. SurfaceView (or a tunneled / protected window) is the usual sink. If L1 playback is black but audio works, bisect: license OK (control) versus secure path / protected buffer (media) versus the window not being protected (render).
Offload, MMAP and A/V sync
Three ideas that interviews smash together: compressed offload (DSP plays music so the AP can sleep), AAudio MMAP (shared memory, low latency), and A/V sync (timestamps). They share a clock story. They are not the same path.
Compressed offload
Extractor hands AAC/MP3/FLAC (as advertised) to an OFFLOAD AudioFlinger thread. Audio HAL + DSP decode. No PCM mix on the AP. Gapless and effects are historically the sharp edges.
AAudio MMAP
PCM in a shared burst buffer with the HAL. Fewer Binder/wakeups than a classic track. Still PCM; still software-visible. Built for latency, not for "decode MP3 on the DSP."
A/V sync
Each buffer has a PTS. The renderer waits until PTS ≈ now + pipeline latency. Audio HAL timestamps are usually the master on phones. Video is held or dropped to match.
Offload is sending a finished mixtape to a warehouse boom-box and going home (AP sleep). MMAP is standing at a small live desk with a short cable (low latency). Sync is the drummer's click: video dancers watch the audio click, not the other way around, unless you are in a tunneled TV chute with a shared hardware click.
Timestamps
AudioTimestamp from AudioTrack.getTimestamp (or AAudio clock) gives a frame position plus a CLOCK_MONOTONIC time. The video renderer converts a video PTS into the same timeline, adding decoder + display latency. NuPlayer and ExoPlayer both do this; they differ in code, not in physics. Tunneling moves the comparison into the HAL/display.
Why VoIP cannot offload like music
- Codec and direction VoIP is PCM (or a conversational codec) in both directions with AEC, NS, AGC. Compressed music offload is one-way decode of a file codec on the DSP.
- Latency Conversational budget is tens of milliseconds end-to-end. Deep buffer and offload periods are built for power (often tens to hundreds of ms of buffering).
- Routing Voice strategy, earpiece / HFP / telephony TX, and possible in-call mixing. Offload threads are MEDIA to a speaker or A2DP sink.
- Interactivity You must start, mute, and switch devices immediately. Offload pipelines flush slowly; policy will not put a call there.
VoIP therefore asks for FastMixer or AAudio MMAP (and the voice usage). That costs AP power — the correct trade. Putting a call on compressed offload is how you get echo, huge mouth-to-ear delay, or "I cannot hear the far end after a route change."
dumpsys media.audio_flinger shows a Mixer thread still running with an AAC file, you did not offload — look at HAL advertised formats, effects that block offload, and policy.Debug: dumps, metrics, no-sound vs no-video
Name the plane, tap the layer, bisect. Audio and video fail independently more often than together. A single Perfetto trace plus the media dumps beats a day of guesswork. Kernel ALSA and IRQ: Linux Kernel & BSP. Power rails when the bug is drain: Power and thermal.
A theatre dark: is the soundtrack missing, the picture missing, or both running but the lips wrong? Those are three different crews (AudioFlinger, codec/Surface, sync). You do not rebuild the building (factory reset the codec HAL) until you know which crew is late.
Real dumpsys commands
adb shell dumpsys media.audio_flinger # PlaybackThreads, tracks, HAL, standby, underruns
adb shell dumpsys media.audio_policy # devices, strategies, focus, volumes, phone state
adb shell dumpsys audio # combined audio view on recent releases
adb shell dumpsys media.player # MediaPlayer / NuPlayer instances
adb shell dumpsys media.extractor # extractor process, open files / MIME
adb shell dumpsys media.codec # C2/OMX components, active instances
adb shell dumpsys media.metrics # mediametrics recordings (name can be media.metrics)
adb shell dumpsys media_session # sessions, buttons, priority
adb shell dumpsys media.camera # only if the source is a camera Surface
adb shell dumpsys SurfaceFlinger # layers, fences — video render
adb shell dumpsys drm # DRM HAL / sessions when present
# Live log tags (keep short; these are noisy)
adb logcat -b all -s AudioFlinger AudioPolicy MediaCodec CCodec NuPlayer ExoPlayer MediaDrm
# Perfetto: audio tracks, codec, SurfaceFlinger, CPU, fences (host Perfetto UI, not a CDN in this page)
| Symptom | First taps | Likely plane |
|---|---|---|
| No sound, video OK | media.audio_flinger, media.audio_policy, focus, device, BT A2DP | Audio control or audio media. Not the VPU. |
| No video, sound OK | media.codec, extractor MIME, SurfaceFlinger layer, DRM secure path | Video media or render. Not the speaker. |
| Neither | extractor, player prepare, license, file/network | Control: never started, or encrypted without keys. |
| Both, lips wrong | timestamps, underruns, offload vs mixer, tunnel | Sync. Do not re-encode first. |
| Music drains battery | thread type, offload, FastMixer standby, app CPU | Wrong thread. See power page. |
| Record file silent or black | AudioRecord source, encoder format-changed, muxer start order, camera stream | Record control vs media. |
Bisect: no sound versus no video
- Is the player prepared?
dumpsys media.player/ app logs. If prepare failed, stop — extractor, MIME, or license. - Audio present? Policy device and focus. A ducked or lost-focus track can look like "no sound." A2DP connected but HAL not opened is a route bug — then Bluetooth.
- Flinger actually mixing? Track in
media.audio_flinger, underrun count, thread not in standby while you expect sound. - Video present? Codec instance, output format, frames released with
render=true. SF layer size non-zero, not hidden, not zero alpha. - Secure / DRM? L1 black frame + audio: license versus protected path versus window.
- Sync only? If both dumps look healthy, plot PTS versus audio timestamp in Perfetto / player debug.
Quick revision
- Control plane: extractor, codec config, AudioPolicy route, focus/session, DRM license. Media plane: PCM, YUV, compressed access units. Sync is a third concern.
- Layer cake: app player → MediaSession/AudioFocus → NuPlayer or ExoPlayer → MediaCodec (C2 preferred, OMX legacy) → codec HAL → VPU/DSP → AudioFlinger or BufferQueue/SurfaceFlinger.
- ExoPlayer/Media3 runs in the app process; MediaPlayer is a Binder stub to NuPlayer in mediaserver.
- Playback is always extractor → decoder → renderer. HTTP/DASH only changes how access units arrive.
- Audio: AudioTrack/AAudio/Oboe → AudioFlinger (FastMixer, deep buffer, OFFLOAD, MMAP) → AudioPolicy device → Audio HAL (AIDL IAudio; HIDL older) → ALSA/DSP/codec → speaker/USB/BT.
- Capture is the reverse into AudioRecord; BT SCO/HFP is a device hop, not the whole BT stack.
- AudioPolicy picks strategy, device and volume; it does not mix. AudioFlinger mixes or offloads.
- Focus GAIN/LOSS/DUCK is control; ducking may also scale a track in the mixer.
- Compressed offload lets the DSP decode music so the AP can sleep; VoIP cannot use that path (latency, duplex, AEC, voice route).
- AAudio MMAP is shared-memory PCM for low latency, not MP3 offload.
- Video decode targets a Surface (BufferQueue/BLAST) or ImageReader; vsync latches; fences order VPU/GPU/display.
- Non-tunnel: decoder → SF → HWC. Tunnel: hardware AV path, SF composition skipped; common on TV, rare as the phone default.
- MediaCodec async: onInputBufferAvailable, onOutputBufferAvailable, onOutputFormatChanged, onError.
- Record: mic/AudioRecord and/or camera Surface → encoders → MediaMuxer → MP4. Camera ISP details belong on the camera page.
- Prefer COLOR_FormatYUV420Flexible for CPU YUV; COLOR_FormatSurface for encoder input Surfaces.
- Bitrate mode (CBR/VBR/CQ) and GOP (I/P/B, I-interval) are encoder control; they are not muxer settings.
- C2 uses C2Work in a vendor or media.swcodec process; OMX is the legacy HAL. Read the component name.
- Hardware first, c2.android.* software fallback when profile, secure, or instance limits require it.
- MediaDrm + MediaCrypto + license server; Widevine L1 is TEE + secure path, L3 is software.
- A/V sync: audio timestamps usually master; video frames held or dropped to PTS. Tunneling uses a hardware clock.
- dumpsys media.audio_flinger, media.audio_policy, media.player, media.extractor, media.codec, media.metrics, plus Perfetto.
- No sound vs no video is a bisect: policy/flinger versus codec/Surface versus extractor/DRM versus sync.
- Binder configures; shared buffers and HAL streams carry samples. Do not imply one Binder transaction per PCM period.
- Cross-links: data-flow map, camera ISP, Bluetooth A2DP/HFP internals, frameworks, Binder, power, kernel/ALSA.
Glossary
- AAudio
- NDK audio API. Can use an MMAP shared-memory path for low latency; Oboe wraps it with an OpenSL ES fallback on old devices.
- Access unit
- One compressed audio frame or one video sample (for example a NAL set with a timestamp) as the extractor/codec sees it.
- AudioFlinger
- Mixer and track server in
audioserver. Owns playback and record threads, timing, and the hand-off to the Audio HAL. - AudioPolicyService
- Routing and volume: devices, strategies (media, voice, alarm, accessibility), focus and ducking. Does not mix samples.
- BLASTBufferQueue
- Usual Android 10+ Surface queue: still producer-consumer GraphicBuffers, cheaper SurfaceFlinger transactions than classic-only BufferQueue setup.
- BufferQueue
- Shared pool of graphic buffers connecting a producer (decoder, camera, app) to a consumer (SurfaceFlinger, encoder, ImageReader).
- C2 / Codec2
- Preferred Android codec framework: C2Work items, AIDL component stores, hardware and
c2.android.*software components. - CSD
- Codec-specific data (SPS/PPS/VPS, AudioSpecificConfig) sent as config buffers before the first access unit.
- Deep buffer
- AudioFlinger mixer thread with larger periods, used for ordinary media PCM to save power versus FastMixer.
- DRM / MediaDrm
- Framework API for license sessions and keys. Paired with MediaCrypto on a MediaCodec. Not a player by itself.
- Extractor
- Parser that reads a container and yields tracks plus access units. Does not decode.
- ExoPlayer / Media3
- App-process player. Drives extractors, MediaCodec, AudioTrack and MediaDrm itself. Preferred over MediaPlayer for app video.
- FastMixer
- Low-period AudioFlinger mix thread. Low latency, more AP wakeups. Games and some UI; not the music battery path.
- Fence
- Kernel sync object that signals when VPU, GPU or display has finished with a buffer.
- GOP
- Group of pictures: an I-frame plus following P/B frames until the next sync frame. Controls seek cost and bitrate.
- ImageReader
- Consumer that gives the app CPU-accessible Images (YUV/JPEG) instead of sending buffers to SurfaceFlinger.
- MediaCodec
- Stable encode/decode API. Implementation is C2 or legacy OMX behind one Java object.
- MediaCrypto
- Object that binds a MediaDrm session to a codec so encrypted access units can be decrypted (securely on L1).
- MediaMuxer
- Writes encoded tracks into a container (typically MP4). Does not encode.
- MediaSession
- Transport and metadata surface for players: play/pause, headset buttons, UI, automotive. Does not move PCM.
- MMAP (AAudio)
- Shared-memory playback/capture path between the app (or AAudio service) and the Audio HAL, aimed at low latency.
- NuPlayer
- Native player engine behind MediaPlayer. Lives in mediaserver; uses extractor + MediaCodec + AudioSink.
- Oboe
- C++ wrapper around AAudio with an OpenSL ES fallback on old devices. Not a system service.
- Offload
- Compressed audio sent to the Audio HAL/DSP for decode so the AP can sleep. Music path, not VoIP.
- OMX
- Legacy OpenMAX IL codec path via the OMX HAL. Still seen on some vendor components; C2 is preferred on AOSP 13–15.
- PTS / DTS
- Presentation and decode timestamps on access units. Sync uses PTS against an audio or hardware clock.
- Surface
- Producer handle to a BufferQueue. Decoders, cameras and GL draw into it; SF or an encoder consumes it.
- Tunneling
- Decoder/display path that bypasses SurfaceFlinger composition and uses hardware AV sync. Feature-gated; common on TV.
- VPU
- Video processing unit: hardware encode/decode block behind the codec HAL.
- Widevine L1 / L3
- L1: TEE + secure video path. L3: software DRM. L2 is rare. No vendor key details required in interviews.
- YUV 420 flexible
COLOR_FormatYUV420Flexible: portable 4:2:0 layout for MediaCodec Images. Preferred when the app reads YUV.
Interview questions
Fundamentals
What is the difference between the control plane and the media plane in Android playback?
Control builds and steers the pipeline: extractor track choice, codec configure (CSD, bitrate, colour), AudioPolicy route, AudioFocus/MediaSession, DRM license. Media is the buffers: compressed access units, PCM, YUV. A/V sync is a third concern that uses timestamps on media buffers and clocks chosen at configure time. Mixing the planes is the usual interview fail.
Walk extractor → decoder → renderer for a local MP3.
The player opens the file; the extractor reports an audio track and yields AAC/MP3 access units. MediaCodec (or a DSP offload path) decodes to PCM — unless compressed offload sends the access units straight to the Audio HAL. PCM goes to AudioTrack → AudioFlinger (usually deep buffer or OFFLOAD) → AudioPolicy device → Audio HAL → ALSA/DSP/codec → speaker. There is no Surface and no muxer.
Walk extractor → decoder → renderer for a local MP4 with audio and video.
One extractor, two tracks. Audio as in the MP3 walk (typically PCM via a software or HW audio decoder into AudioTrack). Video access units go to a MediaCodec video decoder whose output Surface is the app view. Frames ride BufferQueue/BLAST to SurfaceFlinger, latched on vsync, then HWC/GPU to the panel. A sync object holds or drops video so PTS matches the audio timestamp clock.
ExoPlayer versus MediaPlayer — who runs where?
ExoPlayer/Media3 is a library in the app process; it talks to MediaCodec, AudioTrack and MediaDrm itself. MediaPlayer is a framework API whose native engine is NuPlayer in mediaserver (Binder). Both end at the same codecs and AudioFlinger. Prefer ExoPlayer for app streaming (DASH/HLS, CENC). Prefer naming NuPlayer when the question is "what does MediaPlayer do under the hood."
What does MediaCodec do, and what does it not do?
It encodes or decodes access units via C2 or OMX. It does not parse MP4 (extractor), does not mix audio (AudioFlinger), does not composite windows (SurfaceFlinger), and does not write a container (MediaMuxer). Configure + start + buffers (async callbacks preferred). Hardware component if possible; c2.android.* software fallback.
What is AudioFlinger versus AudioPolicyService?
AudioFlinger mixes or hands off tracks and talks to the Audio HAL — the media plane for PCM/offload. AudioPolicyService chooses device, strategy, volume and focus behaviour — control. Policy never mixes; Flinger never decides that A2DP just connected. Both live in audioserver. Dumps: dumpsys media.audio_flinger and dumpsys media.audio_policy.
Name the AudioFlinger thread types you should know.
FastMixer (low latency, more AP), deep-buffer Mixer (music PCM, better power), OFFLOAD (compressed to DSP), MMAP (AAudio shared memory), DIRECT (no mix / passthrough). A rejected fast request silently becomes deep buffer — believe the dump, not the app flag.
What is audio focus?
A control-plane lock so two media apps do not blast at once. requestAudioFocus with GAIN, transient loss, or CAN_DUCK. Telephony and alarms can preempt. Apps should pause or duck; policy may also duck the losing strategy in the mixer. Focus does not by itself open an ALSA device.
What is a Surface in the video path?
A producer handle on a BufferQueue (usually BLAST). The decoder or camera dequeues a GraphicBuffer, writes pixels, queues with a fence. SurfaceFlinger or an encoder consumes. It is not a Bitmap. ImageReader is the CPU-facing consumer instead of SF.
What is an extractor versus a muxer?
Extractor: container in → access units + metadata out. Muxer: access units + format in → container (MP4) out. Neither decodes. Playback uses an extractor; record uses a muxer. Transcode uses both, with decoders/encoders in the middle.
C2 versus OMX in one minute.
Both implement MediaCodec. C2 is preferred on AOSP 13–15: C2Work, AIDL stores, c2.android.* / c2.<vendor>.*. OMX is the legacy OpenMAX IL HAL with OMX.* names. Say "C2 preferred, OMX legacy" and read the component name in dumpsys media.codec.
What is compressed audio offload?
The AP sends compressed music (AAC/MP3/…) to an OFFLOAD AudioFlinger thread; the Audio HAL and DSP decode. The AP can sleep. It is the music battery path on the audio-path map. Effects, gapless and format support can block it and leave you on a PCM mixer.
What is AAudio MMAP?
A shared-memory path for AAudio (and Oboe) so playback/capture periods hit the HAL with fewer wakeups and lower latency than a classic AudioTrack mix. It still carries PCM. It is not compressed offload and not a VoIP-incompatible warehouse tape — it is the live desk.
What is MediaDrm for?
Open a DRM session, talk to a license server (app HTTP), and create MediaCrypto for MediaCodec. Widevine L1 uses a TEE and a secure video path; L3 is software. DRM is not a codec and not a container.
Where does Bluetooth sit on the audio path?
AudioPolicy selects A2DP (media), HFP/SCO (voice) or LE Audio as a device. AudioFlinger opens the BT audio HAL. ACL, AVDTP and HFP signalling are the Bluetooth page. Do not recite L2CAP from a multimedia question unless asked.
Where does camera sit on the record path?
As a Surface producer into the video encoder (plus a preview Surface to SF). Sensor, ISP and HAL3 requests are Camera. This page starts at the video Surface already configured as encoder input.
What colour format should you name for portable YUV?
COLOR_FormatYUV420Flexible when the app uses Images/byte buffers. COLOR_FormatSurface when the encoder input is a Surface (camera/GL). Do not hard-require planar 420.
Name the media processes you expect on AOSP 13–15.
audioserver (Flinger + policy), mediaserver (NuPlayer), media.extractor, media.codec and/or a vendor C2 process, media.swcodec, drmserver, mediametrics. App process if ExoPlayer. cameraserver only when a camera Surface is the source.
What dumpsys should you quote for audio versus codec?
Audio: dumpsys media.audio_flinger, dumpsys media.audio_policy, optionally dumpsys audio. Codec: dumpsys media.codec. Player/extractor: media.player, media.extractor. Metrics: dumpsys media.metrics. Video render: dumpsys SurfaceFlinger.
Why is A/V sync not "just decode as fast as possible"?
Audio is a real-time clock (HAL timestamps). Video frames have PTS. If you display every decoded frame immediately, lips drift as decode speed and vsync disagree. Hold or drop so presentation time matches the audio (or a tunneled hardware clock).
Going deeper
How does HTTP progressive playback differ from DASH on this stack?
Both end at extractor → decoder → renderer. Progressive: one URI, one container, rebuffer if the TCP window starves. DASH: MPD control loop, multiple renditions, fMP4 fragments, often CENC/PSSH and a license. Switching a rendition is a control-plane flush/reconfig; the HAL does not parse the MPD. Bytes on the radio are the data-call path, not MediaCodec.
Walk AudioTrack.write from the app to ALSA on a deep-buffer music track.
App copies PCM into the track's shared buffer (Binder set up the track; write is not a Binder per period). AudioFlinger's Mixer thread wakes, mixes this track with others using the policy volume, writes a period to the Audio HAL output. HAL commits to ALSA PCM or a DSP RPC. Codec IC / amp drives the speaker. Policy already selected SPEAKER (or USB/A2DP). If the thread is OFFLOAD instead, the write was compressed AUs, not PCM.
How does AudioRecord get mic samples?
Reverse of playback: mic → analog/digital codec → optional DSP (AEC/NS if the voice path) → Audio HAL input → AudioFlinger RecordThread → shared buffer → app AudioRecord.read or AAudio callback. Source (MIC, VOICE_COMMUNICATION, CAMCORDER) changes preprocessing and routing. BT SCO capture is a different HAL device; see Bluetooth.
What does a volume strategy actually change?
Which curve and which device. MEDIA on A2DP uses the music slider and the A2DP HAL. PHONE uses in-call volume and earpiece/HFP. SONIFICATION can play on speaker even if media is on BT, depending on config. Ducking multiplies the losing strategy. This is policy XML/engine + runtime device state, not a MediaCodec parameter.
Why might two apps with focus still both be audible?
One requested CAN_DUCK and the winner is a transient (nav). Or one uses an enforced/alarm strategy that policy will not mute. Or a bug: an app ignored loss and kept writing; Flinger will still mix a live track. Dump focus owners and the track list together.
SurfaceView versus TextureView for video?
SurfaceView: a separate SF layer, decoder can target it directly, cheaper, better for DRM/protected. TextureView: composed inside the app view hierarchy via GPU, easier transforms, more power and often a copy. Protected L1 content typically needs SurfaceView (or equivalent). Compose/View interoperability is a UI detail; the hop is still a Surface.
What happens on MediaCodec.onOutputFormatChanged during playback?
Mid-stream change: resolution, stride, colour, or after adaptive switch. The player must read the new format, possibly resize the Surface / view, and keep dequeuing. Treating it as an error and releasing the codec is a common app bug that looks like "video stops after a rendition switch."
How do you start a MediaMuxer without racing the encoders?
Configure and start both encoders. Wait for each INFO_OUTPUT_FORMAT_CHANGED, addTrack with that format, then muxer.start(), then writeSampleData. Adding a track after start throws. Writing before start throws. Audio and video PTS should share a timeline (usually elapsed realtime from a common zero).
CBR versus VBR versus CQ — when do you care?
They are encoder control-plane knobs (KEY_BITRATE_MODE), not muxer settings. CBR: stable size for streaming budgets and some networks. VBR: quality for a file-size target; static scenes shrink. CQ: quality floor, size varies. Phone gallery apps often use VBR. A "12 Mbps 1080p30" number is a budget; the media plane may undershoot on a static scene unless CBR is forced. Too high a rate is a thermal/VPU problem; too low is blocky pictures.
Walk a seek on an A/V file hop by hop.
Control: pause renderers, flush both codecs, extractor seek to a sync sample (I-frame / audio frame near the target). Media: discarded GOPs; the video decoder waits for the next keyframe before a clean picture. Sync: audio and video clocks reset so the new PTS maps to "now" plus latency. A seek to a non-sync time still lands on the previous I-frame and may skip P/B until the target. If you forget to flush, you see a brief garbage frame or old audio.
What is CSD and when is it queued?
Codec-specific data: SPS/PPS/VPS for video, AudioSpecificConfig for AAC, and similar. The extractor exposes it as format extras; the player queues it as a codec config buffer (or passes it in MediaFormat) before the first access unit. Adaptive DASH may send new CSD on a rendition switch. Missing CSD is the usual "codec configured, first frame fails" bug.
How do MediaSession and AudioFocus work together?
Focus decides who may make sound. MediaSession is the transport/metadata surface (play/pause, headset, UI, automotive). A session that receives pause should also abandon or duck focus as the product requires; a focus loss should pause the session. Neither moves PCM. Dump dumpsys media_session and dumpsys media.audio_policy together when "the headset button does nothing" or "two players fight."
When does Android fall back to a software codec?
No hardware component advertised for that MIME/profile/level (10-bit, AV1 on an old VPU), secure required but only a clear component exists, or hardware instances are exhausted (too many 4K sessions). The dump shows c2.android.* (or OMX.google.* on a legacy path). Software 4K is a thermal and jank story — see power.
What is a secure codec buffer?
A GraphicBuffer from a secure allocator (C2) or with protected gralloc usage (OMX). The app and often SurfaceFlinger cannot map the pixels. Output stays on a protected composition / trusted display path. You cannot ImageReader L1 video and screenshot it. If the player tries a TextureView, you get black. No vendor key material belongs in the answer.
Oboe versus AAudio — which do you name?
AAudio is the NDK API on AOSP 13–15. Oboe is a C++ wrapper that uses AAudio and falls back to OpenSL ES on old devices. Interview: "AAudio, Oboe as the portable wrapper." MMAP is a path AAudio can take, not a third API. EXCLUSIVE + LOW_LATENCY is how you ask; the server may still give you a shared mixer.
How does vsync drop a late video frame?
SurfaceFlinger latches the newest queued buffer for that layer on vsync. If the decoder missed the deadline, the previous buffer stays — a freeze, not a tear. A tear is a fence/HWC bug (display scanned a buffer still being written). 24 fps on a 60 Hz panel is frame repeat, not a decoder bug. UI jank (Choreographer) is a different path than media decode jank.
What is a persistent input Surface on an encoder?
MediaCodec.createPersistentInputSurface() (or the CameraX equivalent) is a Surface you can reconnect across codec restarts so the camera session does not have to be torn down on every encoder reset. The ISP keeps writing; a new encoder attaches as consumer. Camera HAL3 details stay on Camera.
App ducking versus mixer ducking?
App ducking: the losing player lowers its own volume or pauses on AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK. Mixer ducking: AudioFlinger/policy scales the losing strategy even if the app does nothing. Both can apply. If music does not duck under nav, check focus request flags and policy ducking config, not the AAC decoder.
What does NuPlayer's AudioSink actually talk to?
The sink is NuPlayer's audio renderer. It opens an AudioTrack (PCM) or an offload track (compressed) into AudioFlinger — the same hops as ExoPlayer's audio renderer. It is not a second mixer. When someone says "NuPlayer plays audio," translate to AudioSink → AudioTrack/offload → Flinger → HAL.
How does MediaRecorder map onto MediaCodec + MediaMuxer?
MediaRecorder is a framework wrapper: it picks an audio source (into AudioRecord / Flinger), a video source (camera or app Surface), configures encoders, and drives MediaMuxer. Same hops, less control of GOP and bitrate mode. CameraX VideoCapture is another wrapper. In an interview, draw the hops first, then say which API owns the graph.
Advanced
Why is there not one Binder transaction per PCM period or video frame?
Binder is for configure, start, route, focus and death. Samples ride shared-memory tracks (AudioFlinger), C2 work queues / GraphicBuffers (codecs), and BufferQueue slots (video). A Binder-per-sample design would miss real-time deadlines and burn CPU. Same idea as Sensors FMQ on the map page. See Binder & AIDL.
What is inside a C2 work item that interviews expect?
A C2Work carries input and output C2FrameData (buffers or native handles), timestamps, flags (codec config, EOS, drop), and fences. The vendor component in the codec process runs the VPU, signals the fence, and returns the work. The framework MediaCodec codec maps that back to Java/NDK callbacks. Do not invent ioctl names; offer to read the current AIDL IComponent.
How do hardware codec instance limits show up?
A VPU advertises a max number of simultaneous sessions at a given resolution. A fourth 4K decoder may fail configure or silently pick c2.android.avc.decoder. Symptoms: one app's video is fine, a picture-in-picture or screen record starts and something falls back to software or errors. Dump media.codec instance counts, not the app's "we requested hardware" flag.
Why do audio effects often block compressed offload?
Offload hands compressed AUs to the DSP. An AP-side effect chain (equalizer, virtualizer, some OEM processing) needs PCM. Policy then refuses OFFLOAD and you land on a deep-buffer mixer. Dump thread type plus the effect list. "I inserted an EQ and battery died" is this story. DSP-resident effects can still offload — confirm on the HAL, do not assume.
Who is the clock master in tunneled versus non-tunneled playback?
Non-tunnel (phones): the player matches video PTS to AudioTimestamp from the Audio HAL / AudioTrack; vsync is when SF can show a frame, not the media clock. Tunnel: the audio HAL or display hardware is master; the decoder releases frames to a hardware AV path and SF composition is skipped for that layer. If tunnel is advertised but not actually used, you are on the non-tunnel clock and must not blame HWC for lipsync.
What does a protected composition path actually require?
L1 success is license + secure decoder + protected buffers + a window/layer the compositor will treat as protected (typically SurfaceView, not a GPU TextureView blit into app memory). HWC must support the protected overlay. A black video layer with healthy audio is often "decrypt worked, path did not." Do not describe breaking the path.
Adaptive rendition switch: flush versus seamless?
Same codec, compatible profile, and a stream that allows it: some players reconfigure or append new CSD and keep the instance (closer to seamless). Resolution/profile jump: flush or recreate the codec, new Surface size, brief hold on the last frame. Extractor/DASH is control; a green flash is usually a missing IDR after the switch or a Surface resize race, not AudioFlinger.
Why AEC means VoIP cannot share the music offload graph?
AEC needs a time-aligned reference of what was played and what was captured. Offload decode on the DSP, deep buffers, and A2DP delay make that reference late or invisible to the AP AEC. Voice usage therefore stays on FastMixer or MMAP PCM with the voice HAL preprocessing. Putting a call on OFFLOAD is how you get echo and huge mouth-to-ear delay.
Write the A/V sync presentation formula and what breaks it.
t_present ≈ t_audio_anchor + (PTS_video − PTS_audio_anchor) + latency_comp. If t_present is too far in the past, drop; too far in the future, hold. Breaks: audio underrun (anchor jumps — video freezes then jumps), wrong latency_comp after a route change (A2DP adds tens to hundreds of ms), seek without clock reset, tunnel vs non-tunnel clock mismatch. Tolerance is tens of ms on phones.
OMX state machine versus C2 — what do you still need?
OMX: Loaded → Idle → Executing, allocate buffers on ports, EmptyThisBuffer / FillThisBuffer. C2: create component, configure, queue work, fences, no classic port-state dance. On 13–15 start with C2. You still mention OMX states if the dump shows OMX. names or a vendor that never finished the port.
BLAST versus classic BufferQueue — what changed?
Same producer-consumer GraphicBuffers and fences. BLAST (Android 10+) batches SurfaceFlinger transactions so the app/codec does not pay a full SF transaction per frame the old way. Do not say BufferQueue went away. Decode → BLAST → SF latch on vsync is the phone default non-tunnel path.
How do operating rate and thermal interact with a VPU?
KEY_OPERATING_RATE / priority tell the codec how many fps it must sustain (slow-mo capture, timeshift). A hot SoC may throttle the VPU or fall back, which looks like dropped frames or a surprise software codec. This is a control-plane hint plus a thermal story, not a muxer bug. High bitrate 4K60 encode is the usual bring-up failure.
Why do conferencing encoders disable B-frames?
B-frames need future references, so the encoder reorders and adds delay (higher latency, bigger GOP). Conferencing wants a short GOP, frequent IDR or intra-refresh, and often CBR. Quality per bit is worse; mouth-to-ear budget wins. Playback of a gallery MP4 can use B-frames freely because it is not interactive.
Provisioning versus a license request — which is which?
Provisioning: device/app proves identity to the DRM system once (or rarely) so it can hold keys. License: per-content (or per-period) permission from the studio's license server after PSSH/init data. MediaDrm exposes both. A provisioning failure breaks every title; a license 401 breaks one. Neither is a VPU configure error. No keybox layout in the answer.
Audio HAL AIDL IAudio versus HIDL — what is the interview-safe line?
Current devices: AIDL IAudio (and related AIDL audio types) in a vendor process. Older: HIDL audio HALs. The framework story is the same: AudioFlinger opens streams, policy picks devices. Confirm with lshal / VINTF on that build. Same split as the audio-path map. Do not invent a stream ioctl list.
Why can a screenshot of L1 video be black while the user still sees the movie?
The user sees a protected overlay the display hardware composites. A screenshot or TextureView readback hits unprotectable memory and is black (or blocked). That is the secure path working, not a decoder hang. If the user also sees black, then the overlay never attached — different bug.
How does USB audio attach without becoming a second AudioFlinger?
USB gadget/host notifies policy of a new device; policy reroutes MEDIA (and maybe voice) to DEVICE_OUT_USB_DEVICE. Flinger closes the speaker HAL stream and opens the USB HAL/ALSA PCM. One mixer, new output. Kernel USB audio is kernel/BSP; this page stops at the device hop.
Scenario & debugging
Video plays, there is no sound. Walk the bisect.
- Focus and session:
dumpsys media.audio_policy,dumpsys media_session— ducked, lost, or never requested. - Device: speaker versus A2DP/USB/HFP. Wrong device is a route bug (then Bluetooth if A2DP).
dumpsys media.audio_flinger: is there a track, which thread, underruns, standby?- Extractor has an audio track? Mute in the container is control, not Flinger.
- Offload fail falling back badly, or a 0-volume strategy.
Do not start at the VPU. This is the no-sound half of the debug section.
Audio plays, the picture is black or frozen. Walk the bisect.
dumpsys media.codec: video component alive, output format, errors.- Extractor MIME and first IDR — a missing keyframe after seek looks frozen.
- SurfaceFlinger: layer size, hidden, alpha, fences.
- DRM: L1 black + audio → license OK versus secure path versus TextureView.
- Player releasing output with
render=falseby mistake.
Audio health only proves the extractor started, not that video buffers reached SF.
Neither audio nor video starts. Where do you look first?
Control plane. Prepare/extractor errors (dumpsys media.extractor, media.player), unsupported MIME, network DataSource failure (then data-flow), or DRM license/provisioning. If prepare never completed, Flinger and SF dumps will look idle and that is expected.
Both play, but lips lead the voice by ~80 ms after a BT connect.
Sync, not codec. A2DP (or LE) added output latency; the player did not update latency_comp from the new AudioTimestamp / HAL latency. Dump the route change and timestamps. Do not re-encode. Full A2DP codec delay lives on Bluetooth; this page owns the PTS math.
Screen-off music kills the battery after a BSP drop.
Suspect offload never engaged: dumpsys media.audio_flinger shows Mixer/FastMixer still running, AP not in suspend. Causes: HAL stopped advertising the format, an effect on the chain, policy flag, or the app forced PCM. Confirm rails on power. Same tip as the audio-path map.
The file is AAC; you expected OFFLOAD; the dump shows a Mixer thread.
Policy or HAL refused offload: format not in the offload profile, gapless/gap requirements, an AP effect, a forced usage that is not MEDIA, or a device (some USB) without DSP decode. Fix the advertisement or drop the effect. Do not "fix" it by making VoIP offload.
Recorded MP4 has video, audio track is silent.
AudioRecord source wrong or muted, voice/CAMCORDER preprocessing, permission, or the audio encoder never got INFO_OUTPUT_FORMAT_CHANGED so the muxer has a track with no samples (or you started muxer before audio format). Dump AudioFlinger record threads and whether writeSampleData ran for the audio track index.
Recorded MP4 has audio, video is black.
Camera video Surface never attached, encoder colour/Surface mismatch, no IDR in the file, or you muxed before video format-changed. Preview can still work (second stream to SF). Do not debug the ISP 3A loop until the encoder dump shows input frames — then go to Camera.
A2DP headset connected; phone speaker is silent; headset is silent too.
Policy moved MEDIA to A2DP; the BT audio HAL stream failed to start. Flinger may show a track on a dead output. Bisect: policy device = A2DP, Flinger HAL error, then HCI/AVDTP on Bluetooth. Forcing speaker in policy is a workaround, not a codec fix.
Widevine L1 title: audio OK, video black, license HTTP 200.
Control (license) succeeded. Media/render: secure decoder missing (fell back to L3/clear and the studio blocked pixels), protected buffers not used, or the sink is TextureView/ImageReader. Check MediaCodec secure flags and the window type. Do not ask for vendor keyboxes.
media.codec dies in the middle of a movie; the app sees onError.
Vendor C2/VPU crash. Tombstone the codec process, not the app. After restart, the player must recreate MediaCodec (and often the Surface). Recurring death at one resolution is a firmware/HAL bug. Isolation worked: audioserver should still be up — that is why the process split exists.
After seek, audio continues and video stays on the old frame for a second.
Video decoder waiting for the next IDR; audio flushed to the new time. Either the seek index landed far from a keyframe (long GOP) or the player rendered the last old buffer. Flush both codecs and hold video until the first post-seek keyframe. Not an AudioPolicy bug.
VoIP sounds fine on speaker; after HFP connect you hear echo.
Voice route changed; AEC reference is now the HFP path with different delay. Confirm FastMixer/MMAP still, not OFFLOAD. Then the BT SCO/HFP hop on Bluetooth and the voice HAL preprocessing. Do not "fix" echo by enabling music offload.
A take-home recorder crashes on the first frame at muxer.start or writeSampleData.
Started the muxer before both encoders emitted output format, or wrote samples before muxer.start(), or addTrack after start. Teach the format-changed barrier. This is control-plane API order, not a VPU defect.
DASH switch: brief green frame, then recovery.
New rendition without an immediate IDR, or Surface resize with an uninitialised buffer shown, or a colour-format change ignored in onOutputFormatChanged. Flush/hold on the last good frame until a keyframe. Green is often uninitialised YUV, not "the speaker path."
Deep-buffer music underruns when a game starts a FastMixer track.
Shared output / mixing capacity or a thread-priority fight. Dump both tracks and thread types. The game is correctly on FastMixer; the music should stay deep or offload. If policy pulled music onto the fast mixer, power and glitches follow. Look at sharing and device, not the MP3 bitrate.
Software decoder is in use for 1080p AVC on a flagship; hardware exists in lshal.
Secure required but HW secure not advertised, profile/level (High 4:4:4, 10-bit) mismatch, instance limit, or the player hardcoded c2.android.avc.decoder. Read the component name and why the selector skipped hardware. Then thermal: software 1080p is survivable, 4K is not.
How would you structure "trace playback of a DASH Widevine title" in 90 seconds?
One sentence each: control (MPD, track select, MediaDrm license, codec configure, policy device, focus); media (fMP4 AUs → C2 decrypt/decode → AudioTrack/Flinger and Surface/BLAST/SF); sync (audio timestamps master unless tunneled). Offer dumps per layer. Point radio bytes to data-flow, ISP to camera, A2DP internals to Bluetooth.