Lib-Media is the media library for HuxerUI. It brings media playback, platform image/video selection, saving to the system photo library, headless audio/video encoding and decoding, container I/O, and decoded PCM output into one C++ library.
Link HuxerUI::Media and use APIs in huxerui::media. Register the Install application hook
for file/URL playback and photo-library access. Codecs, container I/O, and PCM output can run independently of that hook,
a UI runtime, or a window.
Repository: HuxerUI/Lib-Media.
- Capabilities
- Platform support
- Integration
- Media playback
- Media selection and saving
- Media decoding
- Media encoding
- Media containers
- PCM playback
- Preview, builds, and validation
- Repository layout
- Roadmap
| Capability | Current status | Public entry points |
|---|---|---|
| Audio/video playback | Available on Android, iOS, macOS, Windows, Linux, and Web | UseMediaPlayer(), MediaSource, VideoSurface() in media_player.h |
| System image/video selection | Available on Android and iOS | UseMediaLibrary(), MediaLibrary::PickAsync(), and SystemMediaPickerOptions in media_library.h |
| Browse the system photo library | Android and iOS with media read access | MediaLibraryPicker(), album and paged asset queries, image textures, and change notifications in media_library.h |
| Save images/videos to the system library | Available on Android and iOS | UseMediaLibrary(), SaveImageAsync(), SaveVideoAsync() in media_library.h |
| Audio and video decoding | AAC-LC, Opus, Vorbis, FLAC, MP3, H.264, HEVC, VP8, VP9 profile 0, and 8- or 10-bit SDR AV1 where available. macOS and iOS also support mono/stereo ALAC. | AudioDecoder, VideoDecoder, exact timestamps and decoded frames in media_codec.h / media_format.h |
| HEVC encoding and decoding | Main and Main10 adapters for all six platforms. Linux Main/Main10 CPU round trips and preview export passed under WSL. See the HEVC matrix for device and runtime coverage. | CodecId::Hevc, VideoEncoder, VideoDecoder, and VideoPixelFormat::P010 |
| ProRes encoding and decoding | macOS supports progressive 422 Proxy, LT, 422, HQ, 4444, and 4444 XQ. The MOV round trips cover P210, 16-bit packed alpha, and LPCM timing. Compatible iOS devices can decode standard 422. | CodecId::ProRes, VideoPixelFormat::P210, VideoPixelFormat::Ayuv16 |
| AV1 encoding | Optional desktop libaom backend for Main 8 and Main 10 SDR. Encode, fMP4 seek, and decode verified on macOS. | CodecId::Av1, AV1 setup |
| GPU video | SDR H.264 and HEVC Main platform frames and SDK texture input on macOS, Android, iOS, Windows, and supported Web browsers. Windows x64 passed H.264 GPU transcode and SDK texture encoding for H.264 and HEVC Main. See GPU video for platform coverage. | VideoStorage::Platform, MakeExternalTexture(), and MakeVideoFrame() |
| Decoded audio and video playback | #102, Android, iOS, macOS, Windows, Linux, and Web | DecodedPlayback in media_playback.h |
| AAC-LC audio encoding | Implemented; Windows/Linux native checks and Android/Web builds validated; macOS native tests passed; iOS validation pending | AudioEncoder, AudioEncodeFormat, and AudioEncodeSummary in media_codec.h |
| FLAC and MP3 encoding | Optional libFLAC and libmp3lame backends. FLAC supports multichannel 16- or 24-bit PCM; MP3 supports mono/stereo MPEG-1 Layer III CBR with gapless trim. | Build and platform coverage |
| H.264 video encoding | Implemented; Windows/Linux native and Chrome C++/WASM round trips validated; Android build validated; macOS native tests passed; iOS validation pending | VideoEncoder, VideoEncoderConfig, H264Profile, and VideoEncodeFormat in media_codec.h |
| Codec capability discovery | Typed AAC-LC and H.264 snapshots, plus per-codec audio decoder queries for Opus, FLAC, and MP3. Support and reported limits depend on the adapter. | QueryCapabilities() on the four codec classes and AudioDecoder::QueryCapabilities(CodecId, ...) in media_codec.h |
| Container demuxing and muxing | MP4/M4A/fMP4, QuickTime MOV, Matroska, WebM, WAVE/RF64/Wave64, AIFF and CAF LPCM, CAF ALAC, ADTS, Ogg Opus or Vorbis, and native FLAC/MP3 with tag and cover copy | MediaDemuxer and MediaMuxer in media_container.h |
| Additional import and subtitles | Single-program MPEG-TS, AVC/HEVC Annex B, classic AVI, and SubRip or WebVTT cue copy with MKV | Import and remux, standalone subtitles |
Platform selection and saving implement #125. Selected media is returned as
SDK FileReference values, which can be retained for reading, imported to local files, or passed to MediaSource for
playback of supported audio/video content. Saving takes a readable local File and creates a new system-library asset.
| Platform | Playback backend / video output | Platform selection | Saving | Headless decoder |
|---|---|---|---|---|
| Android | Media3 ExoPlayer / TextureView | System Photo Picker; legacy ACTION_PICK gallery fallback |
MediaStore on Android 10+ | NDK MediaCodec |
| iOS | AVFoundation / AVPlayerLayer | PHPicker on iOS 15+ | Photos add-only access on iOS 15+ | AudioConverter / VideoToolbox |
| macOS | AVFoundation / AVPlayerLayer | Unavailable | Unavailable | AudioConverter / VideoToolbox |
| Windows | Media Foundation MediaEngine / D3D11 frame server and HWND swap chain | Unavailable | Unavailable | Media Foundation transforms (experimental) |
| Linux | GtkMediaFile / GdkTexture through HuxerUI ExternalTexture | Unavailable | Unavailable | GStreamer with installed plugins |
| Web | HTMLMediaElement / HTML video element | Unavailable | Unavailable | WebCodecs |
Android's library minimum is API 23; playback uses Media3 1.9.3 resolved by Gradle. Linux builds require GTK 4.14+,
libpulse, and GStreamer 1.24+ app/audio/video development packages. Linux file/URL playback needs a working GTK media
backend. Windows playback needs Media Foundation components and
D3D11-capable hardware. Playback container, codec, and streaming-protocol support follows the platform backend.
Applications own network permissions, transport-security policy, browser CORS/mixed-content rules, and any background
playback or audio-session configuration.
Selection and saving have independent availability. On unsupported platforms, their capability query returns
max_selection_count = 0 and can_save = false; operations return Unsupported. Playback remains available through
its own adapter. See selection limits and compatibility for Android differences.
Lib-Media uses C++20 and the public HuxerUI SDK. Playback and photo-library access use ApplicationContext,
AppOptions::application_hooks, and window platform factories. System photo-library access also uses the SDK's
shared Result type, callback-to-Task bridge, platform file-reference factories, and window presentation coordination
listed in the SDK integration guide.
Clone the library beside your application:
git clone https://github.com/HuxerUI/Lib-Media.gitAfter creating your application target, add the library through the HuxerUI CMake helper:
huxerui_use_library(your_app
TARGET HuxerUI::Media
PATH "${CMAKE_CURRENT_SOURCE_DIR}/../Lib-Media"
)For playback and photo-library access, register the installation hook in the application's startup unit.
App below is your root View function:
#include <huxerui/huxerui.h>
#include <huxerui/media_player.h>
#include <huxerui/media_library.h>
huxerui::View App();
const huxerui::Application application{
App,
{.application_hooks = {huxerui::media::Install}},
};The hook registers platform integration. Put the UI components below in codegen-enabled C++ sources with the
corresponding headers included. The preview application provides a complete integration.
For headless decoding, include <huxerui/media_codec.h> and see Media decoding.
For time-based thumbnail extraction, read frames with VideoDecoder::TryRead() and use
MakeExternalTexture(frame, options) on selected frames. See Timeline thumbnail extraction.
Obtain handles through UseMediaPlayer() or UseMediaLibrary() during composition. Each handle belongs to its
owning composition scope and UI thread; retaining a copy does not keep its session active after unmount. Start commands
from UI events or committed Lifecycle work. Run asynchronous operations through a TaskScope on the owning UI thread.
Playback commands return bool for acceptance and report subsequent platform state through snapshots and events.
Selection and saving return Tasks yielding MediaLibraryResult<T>, the SDK's Result<T, MediaLibraryError>. Check
Succeeded() before reading Value() or Error(); reading the wrong branch throws std::logic_error.
MediaPlayer plays local files, retained FileReference values, and HTTP/HTTPS sources. Audio playback needs no video
view. Mount VideoSurface(player) when video output is needed, and compose your own controls.
using namespace huxerui;
using namespace huxerui::media;
[[huxerui::composable]]
View PlayerPane() {
auto player = UseMediaPlayer();
auto notice = UseState(std::string{});
player.OnError([notice](const MediaError& error) { notice = error.message; });
player.OnEnded([notice] { notice = "Playback finished."; });
return Column {
VideoSurface(player).With(Frame{.height = 240.0F}),
Row {
Button("Load").OnClick([player, notice] {
if (!player.Load(MediaSource(File("/absolute/path/to/video.mp4")))) notice = "The player is unavailable.";
}),
Button("Play").OnClick([player, notice] {
if (!player.Play()) notice = "Playback cannot start for the current media.";
}),
Button("Pause").OnClick([player, notice] {
if (!player.Pause()) notice = "Playback cannot be paused right now.";
}),
}.With(Spacing(8.0F)),
Text(notice),
}.With(Spacing(12.0F), CrossAlign(CrossAxisAlignment::Stretch));
}Replace the example path with an accessible file. Use MediaSource(reference) for picker-provided content, including
Web files. A network source is MediaSource(MediaHttpSource{"https://your-server/video.mp4", {}}).
Load()replaces the source and entersLoading; it does not start playback automatically.Play()can record playback intent while loading.Pause()preserves the current source and position;Clear()releases the source. Loading and clearing preserve volume, mute, and looping preferences.Snapshot()observesMediaPlayerState, including lifecycle status, progress, seekability, buffering/seeking flags, metadata, preferences, and fatal errors. Time values useMediaTime, a duration in double-precision seconds. Missing duration or metadata means unknown; an empty reported buffer list means no buffered ranges are reported.SeekTo()requires known seekability and clamps to a known duration. One platform seek runs at a time; subsequent requests collapse to the latest target. Position comes from the backend. Looping requires a finite, seekable source.OnProgress,OnEnded, andOnErrorare composition-bound subscriptions and allow multiple subscribers. Extra arguments are Lifecycle dependencies. Capture stable State handles when no dependencies are supplied. Progress delivers an initial snapshot, samples about every 250 ms, and coalesces significant updates.- Fatal errors enter
Failed; retry by loading a source again. Recoverable errors are delivered throughOnError.Endeddenotes natural completion; successful loops do not emit it. Platform interruptions may prevent playback while preserving intent, and resumption remains subject to platform policy.
Disconnected commands return false and are not queued. Invalid source arguments, nonfinite/negative seek positions,
or volume outside [0, 1] throw std::invalid_argument. Stale callbacks from replaced sources or retired sessions are
ignored. See media_player.h for complete command, state, and subscription contracts.
Give VideoSurface bounded layout. It provides no controls, autoplay, or fullscreen behavior. A player can have one
mounted surface; mounting a second is rejected. Removing the surface does not pause playback or release the source,
while unmounting the player's owning scope disconnects the session. VideoSurfaceProperties supports ImageFit and
horizontal/vertical Start, Center, or End alignment; Stretch is invalid for content alignment.
The player retains its source while the backend uses it. Android uses platform URIs; Web creates object URLs from browser
File objects; desktop and Apple adapters use AsFile() while retaining the reference. Sources without a platform-readable
location return Unsupported. Raw sequential streams and custom stream providers are not accepted.
Custom HTTP headers currently return Unsupported on every adapter. Android includes progressive ExoPlayer playback,
without the optional HLS/DASH modules. Browser playback may require a user gesture and can report PlaybackNotAllowed.
The library does not configure process-wide Apple audio sessions or add background services.
Playlists, speed control, track/subtitle selection, DRM, casting, downloads, PiP, system media controls, and raw decoded frame/PCM input are outside the file and URL player. Use codec sessions for decoded CPU output and DecodedPlayback to play its PCM frames.
MediaLibrary opens the platform image/video picker, browses the system photo library, and publishes local images
and videos. Use UseMediaLibrary() to obtain the handle for these operations.
PickAsync() opens the system picker with SystemMediaPickerOptions, which accepts Images, Videos, or
ImagesAndVideos and a positive selection_limit.
Its Task yields MediaLibraryResult<std::vector<FileReference>>. User dismissal succeeds with an empty vector; failures
carry MediaLibraryError and are never represented as empty successful selections.
using namespace huxerui;
using namespace huxerui::media;
[[huxerui::composable]]
View SystemMediaPickerPane() {
auto library = UseMediaLibrary();
auto tasks = UseTaskScope();
auto files = UseState(std::make_shared<std::vector<FileReference>>());
auto notice = UseState(std::string("No media selected."));
return Column {
Button("Choose media").OnClick([library, tasks, files, notice] {
tasks.Launch([library, files, notice]() -> Task<void> {
auto result = co_await library.PickAsync(SystemMediaPickerOptions{});
if (!result.Succeeded()) {
notice = result.Error().message;
} else {
auto selected = std::move(result).Value();
notice = selected.empty() ? "Selection dismissed." :
"Selected " + std::to_string(selected.size()) + " item(s).";
if (!selected.empty()) files = std::make_shared<std::vector<FileReference>>(std::move(selected));
}
});
}),
Text(notice),
}.With(Spacing(8.0F));
}The example retains selected references in composition state; dismissal preserves the previous selection. References
remain usable after picker dismissal and session unmount. Android retains SDK URI access; iOS copies provider files
into SDK-owned temporary storage. Keep a reference alive while using its projected path. Metadata may be unknown, and
references do not promise access after process restart. Prefer OpenReadAsync() or ImportToAsync() for large videos.
Query MediaLibrary::CapabilitiesAsync() when preparing controls. MediaLibraryCapabilities::CanPick() derives
availability from a positive max_selection_count; zero means no platform selection is available. can_save is separate
and can be true even when selection is unavailable. A capability snapshot does not grant permission or reserve UI.
| Selection path | Behavior and limits |
|---|---|
| Android system Photo Picker | Preferred on Android 13+, or Android 11/12 with R SDK extension 2+ and an available picker. Images, videos, and mixed selection use the platform maximum. |
Android legacy ACTION_PICK |
Opens an installed image or video gallery. Reports max_selection_count = 1 and accepts single selection only. |
| iOS PHPicker | Supports images, videos, and mixed selection with the requested positive count limit. |
On legacy Android, Images opens the image gallery and Videos opens the video gallery. ImagesAndVideos first uses
the system chooser to offer those two routes and requires handlers for both. A requested media kind can be unavailable
even when another kind has a handler. No document-picker fallback is implicit, and no vendor-specific mixed-media or
multi-select extras are assumed.
selection_limit defaults to one; zero is invalid. Larger limits enable multiple selection only where supported.
Requests above platform capability return Unsupported before presentation, and returned types/counts are validated.
The library does not silently reduce limits or truncate selections. Selection requests no broad photo-library or
storage-read permission. Applications can explicitly offer the SDK FilePicker as a separate document-selection action.
Obtain a handle with UseMediaLibrary(). Inside a launched Task, save a readable local File source with:
auto result = co_await library.SaveImageAsync(source);
if (!result.Succeeded()) {
ShowError(result.Error().message);
}ShowError is an application callback. Use SaveVideoAsync(source) for video. Both Tasks yield
MediaLibraryResult<void>: success confirms publication and needs no separate scan/notification. Each save creates
another asset and preserves the source. Keep its contents readable and unchanged until completion. To save a selected
reference, first import it to a local temporary file and retain that file until saving completes.
Android 10+ validates the media, streams it into a pending MediaStore entry, and publishes after writing completes;
no storage permission is requested. iOS requires a nonempty NSPhotoLibraryAddUsageDescription in the application's
Info.plist and requests Photos add-only authorization. Missing configuration returns Unavailable; denial returns
PermissionDenied. The preview includes the usage description.
Unmount cancels pending platform requests and retires the session. A surviving application Task receives Unavailable,
while Task cancellation suppresses delivery. A platform picker or permission prompt may remain visible until the system
closes it. Platform selection shares the SDK's window presentation coordination with FilePicker.
Canceling a save cannot undo committed publication. Android attempts to delete an unfinished pending entry, subject to
provider cleanup failures. Once an iOS Photos transaction is submitted, it may finish after cancellation; its staged
source remains retained until completion. Partial selection results are released if materializing any item fails.
See the media library guide and media_library.h for details.
MediaLibraryPicker() provides an in-app Recents and album grid with ordered selection, video playback,
and pinch-to-zoom photo preview. Mount it in a bounded view and receive the selected FileReference values
through its callbacks. Apps that provide their own UI can use the same paged queries, texture loading, and
MediaLibrary::OnChanged() invalidation. See the browsing setup
for the application permission declarations.
AudioDecoder and VideoDecoder are move-only sessions with bounded queues. Supply complete access units from a source
or demuxer. The audio decoder produces S16 or F32 PCM from AAC-LC, Opus, Vorbis, FLAC, or MP3, including
supported 5.1 and 7.1 mappings for Opus, Vorbis, and FLAC. The video decoder
produces CPU YUV by default from length-prefixed H.264 or HEVC. macOS, Android, iOS, and Windows can also return
retained platform images for SDR video. Returned frames remain valid after reset and close.
QueryCapabilities(completion)discovers candidates and known limits; see capability queries. The audio decoder also acceptsQueryCapabilities(codec, completion).Probe(config, completion)checks a complete configuration by opening and releasing a temporary decoder.Create()starts a session asynchronously.TrySubmit()copies an accepted packet. OnWouldBlock, keep the packet and retry when the session can accept input.TryRead()returns a format, frame, orEndOfStreamevent on success. An empty optional means no output is ready yet.Finish()drains accepted input and emits oneEndOfStream.Reset()discards queued work and restarts decoding.Close()and destruction retire the session immediately. The optionalcleanup_completedcallback reports teardown after admitted wakeups return. On desktop and mobile platforms, it also follows worker exit.
Each desktop or mobile session and probe has its own worker. Web sessions run on the event loop that created them. Linux uses GStreamer 1.24+ with the installed parser and decoder plugins for the requested codec.
AAC/H.264 fixture decoding passed on an Android 12 device, an iOS simulator, Apple Silicon macOS, Windows 11, Ubuntu 24.04 under WSL, and Chrome through the C++/WASM API. Windows and Linux also check the longer synchronization fixtures with tight output pools. Physical iOS decoding remains unvalidated. See the decoding guide for examples, queue limits, platform requirements, and validation instructions.
Windows and Linux also pass Opus, FLAC, and MP3 packet decoding and PCM preview checks. See the six-platform audio decoder matrix for adapters and validation results.
AudioEncoder accepts contiguous interleaved PCM and returns complete packets, a stream description, and a final
sample summary. AAC-LC is the default. Use AudioEncoderConfig::codec to select optional
FLAC or MP3 encoding. VideoEncoder emits H.264 or HEVC access units with four-byte NAL
lengths and a separate avcC or hvcC description. It takes I420/NV12 for H.264 and HEVC Main, and P010 for
HEVC Main10. On macOS, ProRes takes CPU P210 for 422 or Ayuv16 for 4444 and emits one complete frame per
packet. The optional desktop AV1 backend emits Main 8 or Main 10 temporal units and a separate configuration
record. ProRes · AV1
macOS, Android, iOS, and Windows can encode platform SDR frames with compatible
codecs. Encoded packets can be written through MediaMuxer.
H.264 supports Baseline, Main, and High profiles independently of its B-picture policy: max_b_frames = 0 forbids B
pictures, a positive value requests an upper bound, and std::nullopt allows platform selection. Defaults are High
with zero B pictures. Unsupported controls return an error; Web Main/High requires std::nullopt because WebCodecs
cannot enforce a numeric bound. Use RequestKeyFrame() to request a later IDR without promising an exact frame.
Submit strictly increasing video PTS and drain output in decode order. With B pictures, output PTS can move backward; the encoder restores the corresponding input PTS and duration. DTS is present only when reliable platform timing is available. Accepted CPU input is copied and platform images are retained. Returned packet slices keep output credit across reset and close. Continue draining while submitting to avoid filling either bounded queue.
Linux H.264 encoding requires the installed x264enc and h264parse plugins. Android video encoding requires API 28+;
Main/High numeric B-picture bounds require API 29+. Apple supports zero or automatic B pictures and has independent
iOS/macOS implementations. See the encoding guide for the platform matrix,
queue limits, timing contract, and a bounded producer/consumer example.
All four codec classes expose asynchronous QueryCapabilities(completion). The typed value snapshots separate
library limits from platform-reported limits, describe independent H.264 B-picture policies, and use
CodecSupport::Unknown for facts the platform cannot establish. Use discovery to prepare choices, Probe() to
check their complete combination, and Create() to allocate a session. Discovery does not require a Runtime,
window, or Install(), and does not reserve resources or select a different backend.
MediaDemuxer reads tracks and packets from SDK streams. Each track holds its sample descriptions.
TrackDecodeStart identifies the configuration and any audible start before the corresponding packets.
Packet timestamps use the media clock. MapToPresentation() applies track edits to decoded intervals.
MediaMuxer writes packets and finalizes the output through Finish(). Both sessions are synchronous. Use the container guide
for format mappings, seek behavior, output requirements, and packet ownership. Audio-only MP4 is saved as
.m4a and supports AAC-LC or ALAC packets, supported text tags, front-cover artwork, and exact presentation trim.
All six platforms read and write packed mono/stereo LPCM in AIFF and CAF and copy ALAC packets between CAF and M4A.
AIFF and CAF mappings
DecodedPlayback accepts AudioFrame from a decoder or a PCM generator. Use DecodedPlayback::Create({.audio = audio})
for an interleaved S16 mono or stereo session. The device opens asynchronously and starts paused. Capture Epoch()
before starting the producer. Submit contiguous timestamps with TrySubmitAudio(epoch, frame). An accepted
submission copies the frame so the producer can release its storage.
- Call
Play()and retry the same frame afterWouldBlockwhen playback returns capacity. - Read
Snapshot()for device-observed position, outstanding media duration and underruns. Pause preserves pending media. During starvation the position freezes after the committed tail and playback resumes after refill. A frame blocked by capacity can trigger an earlier start. - Call
FinishAudio(epoch)to seal input.Endedfollows device confirmation of the final media sample and pause.Reset()returns the new token. Usecleanup_completedto observe device release after logicalClose().
Android uses AAudio on API 26+. iOS 15+ and macOS use AVAudioEngine. On iOS, configure and activate the
application's AVAudioSession before creating a playback session with audio. Restore it and create a fresh
playback session after an interruption or invalidated output route. On Web, use the owning browser window event
loop and call Play() from a user gesture. The browser must support AudioWorklet, getOutputTimestamp(), the
requested PCM rate, and the bundled worklet's blob URL in a secure context. Windows uses WASAPI shared output and
the default render endpoint; the system audio engine converts the PCM rate and channel layout to its mix format.
Its playhead follows IAudioClock, while endpoint padding only controls writes. An exhausted device run accepts no
further PCM and is recreated after its media tail is confirmed, so underrun silence does not advance media time.
Linux uses libpulse with an installed PulseAudio-compatible server. Cork acknowledgements preserve queued PCM across
pause. The playhead uses platform stream timing without wall-clock interpolation, and a starved stream is retired after its drain and
final media position are confirmed. A lost connection or output route fails the session even while paused.
Video-only sessions do not require an audio server.
The native playback test is a headless example that plays both generated PCM and the AAC
fixture through this API. With tests enabled, run ctest --test-dir build/tests -R media_playback --output-on-failure
on macOS, Windows, or Linux.
The native executable also runs against the fixture on Android hardware and the iOS Simulator. The iOS
test injects interruption and output-route notifications during playback and while paused. Physical iOS route and
interruption validation is pending. See the
playback contract and device mappings for timing and lifecycle details.
For Linux decoded playback and its native tests:
cmake -G Ninja -S . -B build/linux-tests -DHUXERUI_HOME=/path/to/sdk \
-DHUXERUI_MEDIA_BUILD_TESTS=ON
cmake --build build/linux-tests
ctest --test-dir build/linux-tests --output-on-failureTo try the Web playback sample with the installed SDK, build the WASM test target and serve the build directory
over localhost. Open http://127.0.0.1:8000/tests/playback_wasm.html in Chrome and click Play generated PCM.
The sample also checks synthetic NV12/I420 publication and video scheduling against the PCM clock.
emcmake cmake -G Ninja -S . -B build/web-tests -DHUXERUI_HOME=/path/to/sdk -DHUXERUI_MEDIA_BUILD_TESTS=ON
cmake --build build/web-tests --target media_playback_web_native
python3 -m http.server 8000 --bind 127.0.0.1 --directory build/web-testsUse DecodedPlayback::Create({.video = true}) for video alone and
DecodedPlayback::Create({.audio = audio, .video = true}) for synchronized playback.
Capture Epoch() before producing frames and use that token with TrySubmitVideo(), TrySubmitAudio() and each
track's finish call. Restart the producer with the token returned by Reset(). Stale frames and EOS are rejected.
Drive PresentVideo() from the presentation thread while the session is active. It publishes at most one due frame
per call through a synchronous callback, which can upload the frame to a caller-owned ExternalTexture. Keep pumping
through drain until Snapshot() reports Ended. A session retains up to two video frames, and WouldBlock leaves the
submitted frame with its producer. Pause, Ended, Reset, and Close preserve any already published image. Replace the
texture on a source change if the new epoch should start blank. Synchronized audio starts after Play() and the
first accepted video frame or video EOS, subject to normal audio buffering.
The Windows and Linux Frames previews publish copied RGBA rows through the SDK's platform PixelTexture.
The Linux preview uses the installed AAC/H.264 parser and decoder plugins for its decoded A/V sample.
The Web Frames preview uses WebCodecs in a secure context and publishes through the SDK's VideoFrameTexture.
The preview exercises the library through four tabs.
| Tab | Coverage |
|---|---|
| Video | Local/reference/URL sources, playback controls, progress, seeking, volume, looping, and video fitting |
| Music | Audio playback using the same player API without a video surface |
| Library | System selection, an in-app album picker with photo/video preview, retained references, and publication |
| Frames | Open, preview, and seek decoded video or audio, then copy and save compatible files |
The Library tab offers up to three selections. The system path honors its platform limit, and the in-app picker uses the configured limit. “Save first selection” imports and publishes a retained reference. “Save image” and “Save video” use FilePicker explicitly to obtain a source. Switching tabs unmounts the previous session and cancels its pending work.
The Frames tab uses MediaDemuxer and DecodedPlayback to preview and seek MP4, MOV, WebM, and MKV files
with supported codecs. It switches decoders at sample-description boundaries and applies track edits to decoded
pictures and PCM. The bundled H.264/AAC sample has reordered pictures, uneven frame intervals, and AAC priming.
VP8/VP9 with Opus can use a bounded seek index when Cues are absent. The preview accepts length-prefixed MKV
HEVC with a separate codec configuration and supported SDR AV1 in WebM, MKV, MP4, and fMP4.
On macOS, CPU video previews progressive SDR ProRes 422 and 4444 family MOV with synchronized mono or
stereo LPCM. Compatible iOS devices preview standard 422. Open from Photos on iOS retains the selected video.
Container seek
Switch CPU video to GPU video for supported SDR platform frames. Android can preview directly to
SurfaceStreamTexture. See the frame storage contract and GPU performance comparison.
Open audio plays supported mono/stereo AIFF/CAF/Wave64 LPCM, Ogg Opus and Vorbis, WebM/MKA, FLAC, MP3, and AAC M4A sources. On macOS and iOS it also previews and seeks mono/stereo ALAC in M4A and CAF. Copy Audio keeps compatible AIFF, CAF, WAVE-family, and Vorbis audio in its source container, and retains supported packets, tags, and artwork for FLAC, MP3, and AAC/ALAC M4A. Copy Movie keeps compatible MP4, MOV, WebM, or MKV access units, sample descriptions, timing, and supported metadata. The copy is reopened before the save action becomes available. EBML copies reuse the source Segment tick. Browser input is staged in memory and limited to 128 MiB. MKV copies retain supported subtitle tracks, chapters, tags, and attachments.
The preview integration test covers repeated seeks, presentation edits,
configuration changes, packet-by-packet copy checks, encoded MP4 readback, and WAV sample counts including authored silence.
The test target also exports ProRes 422 + LPCM MOV through P210 and verifies the result with AVFoundation on macOS.
The AIFF/CAF cases check PCM sample counts and seek, plus original ALAC packets, short tails, and audible trim in both
CAF/M4A copy directions. Core Audio and AVFoundation independently read back the audio on macOS.
The multichannel cases decode 5.1 and 7.1 FLAC, preserve speaker positions in PCM export, and verify every channel
after seeks and WAVE-family, AIFF, and CAF round trips.
Encoding and WAV export are built into the test target. Hardware cases use
Probe() for the concrete configuration. The roadmap tracks remaining device acceptance.
From examples/preview, build a platform supported by the installed SDK and host toolchain:
huxerui build android --profile debug
huxerui build ios --profile debug
huxerui build macos --profile debug
huxerui build windows --profile debug
huxerui build linux --profile debug
huxerui build web --profile debugUse huxerui run <platform> --profile debug for interactive testing. For a connected Android device:
huxerui devices android
huxerui run android --device <device-id> --profile debug --java-home /path/to/jdkPlatform shells follow huxerui platform add conventions. Android uses the JDK required by its Gradle project. Apple
adapters compile into the CMake library. The Swift package at platform/ios/Media/ declares the frameworks required by the final iOS app link.
From the library root, with a configured native compiler and SDK:
cmake -G Ninja -S . -B build/tests -DHUXERUI_HOME=/path/to/sdk -DHUXERUI_MEDIA_BUILD_TESTS=ON -DCMAKE_BUILD_TYPE=Debug
cmake --build build/tests
ctest --test-dir build/tests --output-on-failureTests cover playback state transitions, coalesced seeking/progress, looping, stale callbacks, preferences, surface ownership, and media-library result validation, cancellation, late replies, and session retirement. When Node and the SDK Web registry are available, CTest also exercises the Web adapter with simulated media elements. Codec tests use generated AAC/H.264 fixtures and cover queue backpressure, session worker isolation, cleanup ordering, and late WebCodecs callbacks. See the codec validation instructions for standalone and browser runs.
Windows adds WASAPI underrun/clock tests at 48 kHz stereo and 44.1 kHz mono, decoded PCM/video/A/V tests, texture
publication tests, platform muted audio smoke tests, and video geometry tests. To check frame transfer and presentation against
a real source, run build/tests/tests/media_windows_video.exe /path/to/video.mp4 with a short clip under 20 seconds.
It uses an off-screen window, resizes the surface, and waits for natural completion without modifying the source.
Linux Release tests passed on Ubuntu 24.04 under WSL with GStreamer 1.24.2, libpulse 16.1, and WSLg's PulseAudio server.
They cover CPU HEVC Main/Main10 and H.264 round trips, AAC/Opus/FLAC/MP3 decoding, PCM playback, and texture
publication. The standalone preview built with a HuxerUI SDK providing random-access streams. With HuxerUI::testing
available, CTest adds media_container_preview on Windows and Linux to exercise repeated seeks, MP4/MOV export and
readback, audio packet copy, and WAV sample counts. Physical Linux output routes, PipeWire's PulseAudio service, and
measured display/audio synchronization remain device acceptance work.
Device acceptance should cover local/reference/HTTPS playback, seek/end/loop, source replacement, fitting, and platform interruptions; image/video/mixed selection, platform count limits, dismissal, and reading retained references; and image/video publication, denied access, invalid sources, and cancellation. Exercise both legacy Android gallery routes and the mixed chooser. Automated contract tests do not replace platform device or browser verification.
src contains feature directories only. Each feature keeps its public media_*.cpp implementations beside its
private state, validation, and backend contracts. Shared worker execution lives outside the codec and playback modules.
| Path | Contents |
|---|---|
include/huxerui/ |
Public APIs and their full contracts |
src/format/ |
media_format.h implementation: timestamps, PCM/YUV descriptions, and frame validation |
src/player/ |
media_player.h implementation, player state, platform backend contract, channel transport, and video geometry |
src/library/ |
media_library.h implementation, request state, platform transport contract, and payload validation |
src/codec/ |
media_codec.h implementations, capability discovery, shared AAC/AVC initialization utilities, and separate decoder/encoder internals |
src/container/ |
media_container.h implementations, SDK stream I/O, and format-specific readers and writers |
src/decoded_playback/ |
media_playback.h implementation, audio session, device contract, and video scheduling |
src/execution/ |
Desktop and mobile session workers, post-exit cleanup dispatch, and Web event-loop scheduling |
platform/ |
Platform adapters and platform package integration |
examples/preview/ |
Consumer application for playback and photo-library access |
tests/ |
Shared contracts, codec fixtures, and platform checks |
docs/media-library.md |
Photo-library integration and lifecycle details |
docs/media-codec.md |
Codec usage, ownership, platform limits, and validation |
docs/media-container.md |
Container mappings, I/O requirements, and packet contracts |
docs/codec-design.md |
Shared lifecycle design and remaining playback/encoding milestones |
The Lib-Media roadmap tracks remaining work across playback, codecs, containers, and the system media library, with the next integration milestones and acceptance checks.
The codec and decoded-playback design records the shared formats, ownership rules, six-platform lifecycle contract, and delivery order. The AAC/AVC decoding milestone is now implemented, with remaining platform validation called out in the decoding guide.
The next stages of decoded playback (#102) expand device and synchronization measurements. AAC-LC audio encoding and H.264 video encoding have initial implementations; remaining encoder platform validation and additional codecs are later stages of #20. Capability discovery now covers the currently implemented AAC-LC and H.264 adapters.
Existing file/URL playback continues to use platform players. HuxerUI owns general file, task, window, and texture facilities; media-specific behavior stays in Lib-Media.