Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Audio and video

Four widgets over one MediaPlayer: the picture, the controls, both together, and a compact player for sound.

By the end of this chapter you can open a file or a URL in a player, show it with its controls from markup or Java, switch tracks and subtitles, and know which codecs a build decodes.

The module

The widgets are in goldberry-media. Java demuxers read Matroska and WebM, MP4, Ogg, FLAC, WAV and MP3 through MediaIO. The bundled decoders and pixel conversion ship in libgoldberry-media, one library for each target. Add the natives-<target> classifier for each platform your application supports.

Add the stylesheet beside the controls’ own:

var sheets = new ArrayList<>(Controls.stylesheets(theme));
sheets.add(MediaStyles.stylesheet());

The published natives decode royalty-free codecs only: VP8, VP9, AV1 and Theora for video, and Opus, Vorbis, FLAC, MP3 and PCM for audio. MediaCapabilities.current() answers what a build decodes and demuxes, read from the loaded libraries.

A player

A MediaPlayer is the application’s. The widgets show and drive it, and never own it.

import dev.goldberry.media.MediaPlayer;
import dev.goldberry.media.io.Source;

var player = MediaPlayer.builder().build();
player.open(Source.of(Path.of("clip.webm")));
player.play();

open takes a Source.of(path) or a Source.of(uri). Every call returns at once: the engine runs on its own threads and reports back as a PlayerStatus, one immutable value with the state, the position, the duration, the tracks, the volume, the rate and the buffered ranges. player.status() reads the latest and player.onStatus(listener) hears each change. The transport is play, pause, seek(position) or seek(position, SeekMode.KEYFRAME), setVolume, setMuted, setRate from 0.25 to 4 with the pitch following, step(count) for a picture at a time, and close. A seek on a source that cannot seek, or a live one, is dropped and the stream plays on. PlayerStatus.seekable() says which.

setLooping(true), or MediaPlayer.builder().looping(true), plays the source over and over. The player never reaches ENDED, and there is no pause where the source joins back onto its start. The engine reads the start again before the end is heard. The sound and the pictures run on in time across the seam, and the position is the time within the pass that is playing. A pass is as long as its last picture. The sound is fitted to that length: trimmed where it runs over, and padded with silence where it falls short. A source with no picture loops at the end of its sound’s last packet, so an Opus track’s encoder padding, a few milliseconds, is heard at the seam. A source that cannot seek, or a live one, ends anyway.

MediaProbe.probe(source) says what a source holds without playing it. A video track’s TrackParams.Video has its frameRate(), a FrameRate such as 60/1 or 30000/1001, and the Track has its frameCount() where the container records one. MP4 does. Matroska and WebM do not, so for them the count is frameRate.framesIn(duration).

A source’s chapters are on its MediaInfo: chapters() lists them in order, each a Chapter with its start, its end and its title, and chapterAt(position) is the one playing. They are read from Matroska’s chapters, an MP4’s chapter track or chpl list, an MP3’s ID3 CHAP frames, and the CHAPTER001= comments of Ogg and FLAC. nextChapter() seeks to the next one’s start; previousChapter() seeks to the start of the one playing once it has played three seconds, and to the one before it until then. Both return false when there is nowhere to go.

In markup a player is a named object. The application registers it and a node names it with player=:

var named = Named.strict().bind("video.player", player);
var inflater = Widgets.inflater(named, icons, model);

A node with no player to resolve against does not inflate, so the samples below are fragments and the showcase’s video.kdl and audio.kdl are the complete documents.

HDR and wide gamut. A picture in HDR (PQ, as HDR10 is, or HLG) or in BT.2020’s or P3’s primaries is tone-mapped to the window’s SDR as it is drawn, on the GPU and on the CPU alike: its light from the stream’s own transfer function, its colours into BT.709’s, its highlights rolled off from the brightness it was mastered to (1000 nits when it does not say) down to SDR’s white, with hue kept. What a stream says of its colour comes from the codec and the container both; VideoPlanes.colour() hands it to a view that converts planes itself, and ColorDescription is what a decoder an application brings reports.

Tracks, subtitles and the network

A source with two voices or two angles offers a track menu, and player.selectTrack(track) switches over the same frame queue, so the old picture stays up until the new track’s picture covers the position. Text subtitles are read in Java from a SubRip, WebVTT, ASS or MP4 text track, or from a SubRip or WebVTT file through player.loadSubtitles(source). hideSubtitles() turns them off and currentSubtitles() is what shows at the clock. The player does not read bitmap subtitles.

A URL is read through a cache and buffered to a high-water mark, which the seek bar shades. Once the source is open, the cache reads up to half a minute ahead at its bitrate when it has room. A live stream’s ICY title appears in the player’s nowPlaying line. With no audio device, media plays silently.

Bringing a codec

H.264, HEVC, AAC, AC-3 and E-AC-3 are not in the published natives. They play through the operating system’s own decoders, which are DecoderProviders found by ServiceLoader and consulted before the built-in ones:

ProviderCodecsSystem
videotoolbox, audiotoolboxH.264, HEVC; AAC, AC-3, E-AC-3macOS
gstreamer-video, gstreamer-audioThe same, with the decoders installedLinux
mediafoundation-video, mediafoundation-audioThe sameWindows. Set -Dgoldberry.media.mediaFoundation=false to disable
vulkan-videoH.264, HEVC, VP9 and AV1 as supported by the driverSupported Vulkan devices

An application brings its own codec the same way: implement DecoderProvider with name, supports(request) and open(request), and declare provides dev.goldberry.media.codec.DecoderProvider with … in its module. A provider for a patented codec holds the licence for it. MediaPlayer.builder().decoderProviders(list) lists providers by hand, and PlatformDecoders.providers() is the system’s set.

The probe names such a track’s pixel format even so: the published natives neither decode nor parse H.264 or HEVC, so the name is read from the parameter sets in the track’s avcC or hvcC record.

The bundled decoders run in software. setHardwareDecoding(HardwareDecoding.OFF) asks system providers to use software and bypasses providers requiring hardware. The setting applies from the next source opened and is passed to custom providers in each DecoderRequest. To use an external decoder as a last resort, set -Dgoldberry.media.ffmpeg=/absolute/path/to/ffmpeg to an executable installed on the machine.

Nothing larger than 8K is decoded: no side longer than 8192 and no more pixels than 8192 × 4352, the largest picture AV1 and VP9 define. A source whose video states more, or whose decoder hands over more, fails with InvalidData naming the size. PictureLimit holds the two numbers, and a provider an application brings can hold its decoder to them too.

A video sticker

A WebM sticker is a short VP9 video with an alpha channel: each picture’s alpha travels beside it as a second VP9 stream, and the track says so with AlphaMode. The built-in decoder decodes both, so the pictures are transparent where the sticker is, and half transparent where it fades.

VideoAnimation plays one as a picture rather than as a player. It reads the bytes from memory, decodes no sound, holds no thread, and is drawn by the same AnimationView that plays a Lottie sticker:

var sticker = VideoAnimation.of(bytes);
return new AnimationView(sticker, "🎉");

The view plays it on the frame loop, loops it until loops(n) says otherwise, stands on its first picture with autoplay(false) or when the user asks for less movement, and draws it over whatever is beneath it. Each picture is decoded when the frame asks for it, on the UI thread, which costs about a millisecond and a half for a 512×512 sticker. close() frees the decoders, and an animation nothing refers to frees them by itself.

A MediaPlayer plays the same file with its alpha too. video-view draws a picture with alpha on the CPU, over its own background, which media.css makes black: a stylesheet that wants the page to show through sets background-color: transparent on it. The GPU’s video layer draws opaque pictures only, and leaves these to the CPU.

media-player

A video-view with media-controls laid over its foot: the picture, the transport, the error, the stream’s title and the subtitles in one box.

A media-player paused on a lake at dusk, two subtitle lines over the picture, and the controls along its foot: play, the elapsed and remaining times around a seek bar, a subtitles menu reading English, and mute with a volume sliderA media-player paused on a lake at dusk, two subtitle lines over the picture, and the controls along its foot: play, the elapsed and remaining times around a seek bar, a subtitles menu reading English, and mute with a volume slider

A media-player paused, with a subtitle track chosen.

media-player id="video-player" player="video.player" fit="contain"
import dev.goldberry.media.view.MediaPlayerView;

new MediaPlayerView(player);
new MediaPlayerView(player, Fit.COVER, Attributes.NONE.id("video-player"));

The controls hide while the player plays and the pointer rests, 2.5 seconds after it last moved, and come back when it moves. A click on the picture plays or pauses. A failure is shown over the picture in .media-error, and an H.264 file says which codecs it could not play. Subtitles are lines over the foot of the picture, above the controls while they show and lower while they hide. F asks the window to fill its display, and a copy of the player covers the window with the class is-fullscreen.

Attributes

AttributeTypeDefaultWhat it does
playernamed MediaPlayerrequiredThe player to show and drive
fitcontain, cover, fill, nonecontainHow a picture fills a box of another shape, as on image
idstringnoneThe player’s id
classstringnoneClasses on its box

Children are refused.

Styling

The CSS type is media-player, a column with min-height and the backdrop --gb-media-backdrop. Inside it are the video-view, the .media-overlay column pinned to the bottom, media-controls in that, .media-error, .media-now-playing, .media-subtitles and .media-subtitle. The state is on the root as .is-idle, .is-opening, .is-buffering, .is-playing, .is-paused, .is-ended or .is-error, with .is-scrubbing while the seek bar is held, .is-pointer-idle while the controls hide, and .is-fullscreen on the full-window copy. The tokens are --gb-media-*, and media.css fades the overlay on .is-pointer-idle.

A source with chapters notches the seek bar where each starts, and .media-chapter is the title of the one playing, after the elapsed time.

Keyboard

Once the player has focus: Space or K plays and pauses, Left and Right seek five seconds, Up and Down change the volume by five percent, M mutes, L loops the source and stops looping it, Home goes to the start, , and . step a picture back and on, < and > slow down and speed up through 0.25 to 2, and F and Escape enter and leave fullscreen.

Page Up goes to the previous chapter and Page Down to the next.

video-view

A player’s pictures and nothing else: the surface for an application that draws its own controls or none.

video-view player="trailer" fit="cover"
import dev.goldberry.media.view.VideoView;

new VideoView(player);
new VideoView(player, Fit.COVER);

The view follows the player’s status. A picture a paused seek lands on is shown when it is ready, and while the player plays it draws a new picture every frame. With goldberry-gpu on the module path the pictures go through a GPU layer, and a shader converts them from their planes with the stream’s matrix and range. Without it, or where the layer cannot be placed, the view draws converted pictures on the CPU.

Attributes

AttributeTypeDefaultWhat it does
playernamed MediaPlayerrequiredThe player to show
fitcontain, cover, fill, nonecontainHow the picture fills the box. The picture is centred
idstringnoneThe view’s id
classstringnoneClasses on its box

Children are refused.

Styling

The CSS type is video-view. It has no size of its own and grows into what it is given, with flex-grow: 1 and --gb-media-backdrop where the picture does not reach.

On the GPU, a picture’s planes are copied once: the video thread writes them straight into the view’s upload memory, and the window’s thread uploads them as they are, so a 4K picture costs the UI thread half a millisecond. This happens by itself for video-view. An application that draws a player’s pictures with PictureRenderer gets the same by offering the renderer’s memory: player.attachView(PictureForm.PLANES) and then setPlaneStore(renderer.planeStore()) on what it returns.

Keyboard

None of its own. Put a media-controls beside it.

A picture that does not come from a player, such as a call’s video decoded by the application, is shown by PictureView over a PictureSource. A PushedPictures takes pictures from any thread, and the view draws the newest once a frame, as a video-view with the same styling.

var tile = new PushedPictures();
row.add(new PictureView(tile, Fit.COVER));
tile.push(new VideoPlanes(...));   // from the thread that decoded it

A pushed picture’s bytes must stay as they are until two more have been pushed after it. A VideoPicture is drawn as it is. VideoPlanes are shown by the GPU where the window has one, and converted to BGRA on the CPU where it has not, which takes the module’s natives; a picture is converted once however many frames draw it.

audio-player

Compact controls over a player: play and pause, the times, a seek bar, mute and volume, with the stream’s title above and an error below.

An audio-player: play, the elapsed time, a seek bar a third of the way along, the remaining time, and mute with a volume sliderAn audio-player: play, the elapsed time, a seek bar a third of the way along, the remaining time, and mute with a volume slider

An audio-player over the same player.

audio-player id="audio-player" player="audio.player"
import dev.goldberry.media.view.AudioPlayer;

new AudioPlayer(player);

The seek bar is left out for a source that cannot seek, and a LIVE label stands in its place for a stream. While playing, the widget reads the position four times a second.

Attributes

AttributeTypeDefaultWhat it does
playernamed MediaPlayerrequiredThe player to show and drive
idstringnoneThe player’s id
classstringnoneClasses on its box

Children are refused.

Styling

The root carries the class audio-player, and its pieces media-play, media-time, media-seek, media-live, media-rate, media-mute, media-volume, media-now-playing and media-error. The state is on the root as is-playing, is-paused, is-buffering, is-ended or is-error.

media-chapter shows the current chapter title when available.

Keyboard

As media-controls, without the picture keys.

Page Up goes to the previous chapter and Page Down to the next.

media-controls

The transport bar on its own, for an application that lays it out itself under a video-view or drives a player it shows elsewhere.

column {
    video-view player="trailer"
    media-controls player="trailer"
}
import dev.goldberry.media.view.MediaControls;

new Column(List.of(new VideoView(player), new MediaControls(player)), Attributes.NONE);

Play and pause, the elapsed and remaining times, a seek bar that scrubs to keyframes while dragged and lands exactly on release, mute, volume, the rate when it is not 1, and the audio, video and subtitle menus where the source has a choice. All of it is built from the ordinary controls, so it takes the theme and the focus like any other.

Attributes

AttributeTypeDefaultWhat it does
playernamed MediaPlayerrequiredThe player to drive
idstringnoneThe bar’s id
classstringnoneClasses on its box

Children are refused.

Styling

The CSS type is media-controls, a row with --gb-media-gap. Its pieces carry media-play, media-time, media-seek, media-live, media-rate, media-loop, media-mute, media-volume, media-audio-track, media-video-track, media-subtitles-menu and media-fullscreen. The media-loop button shows only while the player loops, and pressing it stops the loop. The state is on the bar as is-playing, is-paused, is-buffering, is-ended or is-error, and is-scrubbing while the seek bar is held.

media-chapter shows the current chapter title when available.

Keyboard

The bar is a focus stop. Space or K, Left and Right, Up and Down, M, L, Home, , and ., and < and >, as on media-player. A key bubbles to the bar from a control inside it that does not want it.

Page Up goes to the previous chapter and Page Down to the next.