Jump to content

Movie Player: Difference between revisions

From OpenBOR
YUV path additions.
Update to hardware acceleration.
 
Line 1: Line 1:
OpenBOR provides a reusable source, playback, and channel system for movie media. The API uses the generic <code>movie_*</code> namespace so additional container or codec support can be added later. The current backend plays WebM files containing VP8 video and optional Vorbis audio.
== Introduction ==


Movie playback and presentation are deliberately separate. OpenBOR advances active movies asynchronously, while creator scripts select one of two presentation paths:
OpenBOR plays WebM movies containing VP8 video and optional Vorbis audio. Movies can supply cinematics, animated interfaces, video surfaces, picture-in-picture layouts, or the main content of a module.


* <code>movie_draw_to_screen()</code> converts the retained YUV frame to 32-bit RGB and copies it into a creator-selected screen. This path supports subscreens, offsets, clipping, scaling, black filtering, and normal drawing order.
The movie system separates playback from drawing. Video and audio decoding run asynchronously on the CPU. The GPU samples the decoded video planes, converts their YUV colors to RGB, and renders the result. Scripts decide when and where to draw the retained frame while the movie channel manages position, pause, speed, repeat, and audio.
* <code>movie_draw_to_yuv()</code> presents the retained frame directly through the hardware YUV output path. This avoids software YUV-to-RGB conversion and is intended for exclusive final-screen presentation.


Neither drawing function advances the movie clock or decoder. Playback, pause, position, speed, repeat, interruption, and embedded-audio controls remain properties of the movie channel regardless of the selected presentation path.
Both <code>movie_draw_to_screen()</code> and <code>movie_draw_to_yuv()</code> use GPU rendering. Their difference is the destination: an OpenBOR screen for composition, or the display for direct presentation.


=== Choosing a presentation path ===
== Choosing a drawing destination ==
 
Neither path is universally superior. Hardware YUV presentation favors efficient, exclusive playback, while 32-bit RGB drawing favors composition and creative control.


{| class="wikitable"
{| class="wikitable"
! Consideration
! Feature !! Screen composition !! Direct display
! <code>movie_draw_to_yuv()</code>
|-
! <code>movie_draw_to_screen()</code>
| Function || <code>movie_draw_to_screen(screen, channel)</code> || <code>movie_draw_to_yuv(channel)</code>
|-
|-
| YUV conversion
| Destination || Main virtual screen or a creator-owned subscreen. || Display window.
| Uploads the decoded Y, U, and V planes to the video backend. Where supported, the renderer or GPU performs YUV-to-RGB conversion and final scaling.
| Converts the decoded YUV frame into a 32-bit RGB OpenBOR screen before presentation.
|-
|-
| CPU and memory cost
| Rendering || GPU video sampling, YUV-to-RGB conversion, scaling, and drawing. || GPU video sampling, YUV-to-RGB conversion, scaling, and presentation.
| Avoids the full software YUV-to-RGB conversion and intermediate RGB frame. This is especially useful for high-resolution or fullscreen movies.
| Uses additional CPU time and memory bandwidth for conversion, plus scaling when the requested dimensions differ from the source.
|-
|-
| Display sizing
| Placement || Movie dimensions and signed destination offsets, clipped to the screen. || Centered presentation using logical display dimensions and the display's stretch setting.
| Uses the WebM display dimensions by default, independently of the internal resolution configured by <code>video.txt</code>.
| Zero width and height follow the destination screen, making the movie naturally conform to a main screen or subscreen.
|-
|-
| Composition
| Composition || Combine movies with sprites, text, effects, and other screen content. || Present one movie frame directly. Each call replaces the displayed window content.
| Owns the final display while active. It cannot be mixed with normal OpenBOR drawing.
| May be placed anywhere in the normal drawing order and combined with sprites, text, effects, or other movie channels.
|-
|-
| Screen effects
| Image controls || Movie resampling and exact-black protection. Apply drawmethod effects when drawing the resulting screen. || Movie resampling and display brightness/gamma correction.
| Does not support destination offsets, clipping, black filtering, or later <code>drawscreen()</code> transformations.
| Supports offsets, clipping, black filtering, subscreens, and subsequent drawmethod transformations.
|-
|-
| Typical use
| Typical use || Video surfaces, captions, interfaces, multiple views, and layered scenes. || Full-window movie playback controlled directly by a script or scene.
| Fullscreen cinematics, high-resolution introductions, logos, and other movies intended to occupy the display by themselves.
| In-world screens, animated interfaces, picture-in-picture layouts, layered cutscenes, and movies requiring overlays or effects.
|}
|}


Both paths use the same WebM demuxer and VP8 decoder. Hardware YUV presentation reduces conversion and composition work after decoding; it does not eliminate video decoding cost. Actual acceleration depends on the active SDL or OpenGL video backend and the capabilities of the target system.
Drawing uses the channel's retained frame. It does not advance playback or request a separate decode. One retained frame may be drawn repeatedly, sent to several screens, or shown through either drawing function. The renderer reuses its uploaded video planes until playback supplies another frame.
 
The movie system has three main parts:
 
* '''Source''' - A streamed path or cached WebM byte buffer identified by a source ID.
* '''Playback''' - One active use of a source, represented by a stable playback object pointer.
* '''Movie channel''' - One of 64 fixed slots that owns playback, timing, decoding, and sound-routing state.
 
Keeping these concepts separate is important. One source may be played several times, each playback has independent state, movie channels are separate from the sound channels used by embedded audio, and destination screens remain under creator control.


== Formats ==
== Formats ==


{| class="wikitable"
{| class="wikitable"
! Component
! Component !! Format
! Current support
! Notes
|-
|-
| Container
| Container || WebM. Supply the complete module path, including its extension.
| WebM
| The supplied path is used exactly. Movie loading does not append an extension.
|-
|-
| Video
| Video || VP8. Use even frame dimensions of at least 2 by 2 pixels. The video track must use a non-stereoscopic mode.
| VP8
| Video track required. Stereoscopic WebM modes are not supported.
|-
|-
| Audio
| Embedded audio || Optional Vorbis, mono or stereo. The engine's music sample-rate range is 11,025 through 48,000 Hz.
| Optional Vorbis, mono or stereo
| Embedded audio is decoded to 16-bit PCM and routed through an ordinary OpenBOR sound channel. Sample rates from 11.025 through 48 kHz are recommended.
|-
|-
| Presentation
| Screen destination || 32-bit OpenBOR screen, including screens created with <code>allocscreen()</code>.
| 32-bit RGB or hardware YUV
| Retained frames may be converted to RGB and drawn into the main screen or any creator-owned 32-bit subscreen. They may instead be presented directly through the exclusive hardware YUV output path.
|}
|}


Source video dimensions must be at least 2 by 2, even on both axes, and small enough for the 32-bit screen renderer to represent safely. Compatibility is checked when the asynchronous decoder opens. Successful <code>movie_load()</code> calls only prove that the source path could be opened or cached.
The decoder selects the first video track and first audio track. Unsupported video or audio codecs reject playback when the decoder opens. If initialization of a supported optional Vorbis track fails, video may continue silently with the reason recorded in the engine log.


Movie functions remain visible on builds compiled without WebM support. Such builds report that movie playback is unavailable and return an empty value instead of opening media.
Loading checks that source data can be opened or cached. Codec and track validation takes place when playback opens asynchronously, so a loaded source can still report a playback-opening error.


== Streamed and cached sources ==
== Sources, playback, and channels ==


<code>movie_load()</code> accepts a loading-mode constant.
Three identifiers serve different purposes:


{| class="wikitable"
{| class="wikitable"
! Mode
! Item !! Returned by !! Purpose
! Constant
! Load behavior
! Playback behavior
! Best use
|-
|-
| Streamed
| Source ID || <code>movie_load()</code> || Identifies a reusable streamed file or cached compressed file.
| <code>MOVIE_LOADING_STREAM</code>
| Copies the path and confirms that the file can be opened.
| Each playback opens an independent packfile position and decoder.
| Long movies, one-time scenes, and memory-sensitive projects.
|-
|-
| Cached
| Playback object || <code>movie_play()</code> || Provides property access and playback control for a movie channel.
| <code>MOVIE_LOADING_CACHE</code>
| Reads the complete compressed WebM file into memory once.
| Each playback reads the shared read-only buffer but still owns an independent decoder and frame queues.
| Short clips, repeated playback, and seek-heavy controls when sufficient RAM is available.
|-
|-
| Automatic
| Movie channel index || <code>movie_get_channel_index()</code> || Selects the movie used by either drawing function.
| <code>MOVIE_LOADING_AUTO</code>
| Caches when the file fits the engine's memory policy; otherwise keeps a streamed source.
| Uses the selected cached or streamed source transparently.
| General-purpose loading when a project does not need to force a policy.
|}
|}


Automatic mode allows cached sources to occupy at most one quarter of total system memory. It also preserves an available-memory reserve of at least one eighth of total memory or 128 MiB, whichever is larger. Cache allocation pressure falls back to streaming. File or pack I/O errors still fail the load instead of being hidden by a fallback.
Movie channels are numbered 0 through 63. <code>MOVIE_CHANNEL_COUNT</code> provides the channel count, and <code>MOVIE_CHANNEL_AUTO</code> requests automatic selection. Automatic selection takes the lowest inactive channel and reports an error when every channel is active. Selecting an explicit index replaces playback on that channel.
 
Cached mode is a '''compressed source cache''', not a decoded frame cache. It removes repeated storage reads but does not remove VP8 or Vorbis decoding cost.
 
Source storage grows dynamically from an initial capacity of 64 records. Source IDs are assigned in ascending order and are not reused during the session. Loading the same path more than once creates another source ID; OpenBOR does not merge duplicate movie-load requests automatically.


One source can back several simultaneous playbacks. Cached playbacks share the source bytes, while every playback retains independent position, speed, repeat, dimensions, offsets, movie channel, and sound channel state.
The playback pointer identifies an engine-owned channel object. Its address remains stable while the movie system is running, including when the channel is inactive. Reusing the channel replaces its playback state. Coordinate channel ownership between scripts, and use <code>MOVIE_PROPERTY_ACTIVE</code> to check whether a channel is playing. Release playback with <code>movie_stop()</code>; the engine manages the channel object's storage.


== Movie channels ==
Source storage is separate from the 64-channel playback bank and grows as sources are loaded. Source IDs increase during the session and are not reassigned after unloading. Loading the same path twice creates two source IDs. One source may be played on several channels, with independent timing, presentation settings, and audio routing.


OpenBOR exposes one bank of 64 movie channels numbered <code>0</code> through <code>63</code>.
== Loading modes ==
 
* Automatic playback selects the lowest inactive movie channel.
* Automatic playback fails when all 64 channels are active.
* Explicit channel selection forces playback onto that slot and stops its previous occupant.
* Stopped or completed playback immediately releases its source reference and marks the channel inactive.
* The 64-bit active mask allows OpenBOR and scripts to skip inactive channels.
* Channel objects remain structurally stable until movie shutdown, even while their playback state is replaced or reset.
 
Movie channels have no priority system. Explicit selection is a forced replacement. The public constants <code>MOVIE_CHANNEL_COUNT</code> and <code>MOVIE_CHANNEL_AUTO</code> report the current capacity and automatic-selection value.
 
=== Practical limits ===
 
The 64-channel capacity provides consistency and creative headroom, not a realistic expectation of 64 simultaneous decoders. Every active movie may own demux, video-decoder, audio-decoder, packet-queue, frame-queue, conversion, scaling, and sound-stream resources. Available CPU time, memory bandwidth, storage speed, resolution, frame rate, and target hardware establish the practical limit.
 
Most projects should expect one or two simultaneous high-resolution movies to be a substantial workload. The fixed channel bank prevents an arbitrary API ceiling from becoming the first limitation.
 
== Playback defaults ==
 
Every successful <code>movie_play()</code> begins with the following state:


{| class="wikitable"
{| class="wikitable"
! Setting
! Constant !! Source storage !! Use
! Default
! Behavior
|-
| Movie channel
| Automatic
| Uses the lowest inactive movie channel unless a channel is supplied.
|-
| Presentation target
| None
| Playback advances without drawing until a script calls <code>movie_draw_to_screen()</code> or <code>movie_draw_to_yuv()</code>.
|-
| Width and height
| <code>0</code>, <code>0</code>
| RGB drawing adopts the corresponding destination-screen dimensions. Hardware YUV presentation uses the WebM display dimensions. Explicit positive values select the requested presentation size.
|-
| X and Y offset
| <code>0</code>, <code>0</code>
| Places the prepared frame at the destination origin.
|-
| Speed
| <code>1.0</code>
| Normal forward playback.
|-
| Paused
| <code>0</code>
| Playback clock and decoding advance normally.
|-
| Repeat
| <code>0</code>
| Stops when the movie reaches its terminal frame.
|-
|-
| Interrupt
| <code>MOVIE_LOADING_STREAM</code> || Retains the file path. Each playback opens its own file position and decoder. || Playback that reads its compressed data from the module as needed. This is the default.
| <code>1</code>
| Normal movie-skip input stops playback.
|-
|-
| Black filter
| <code>MOVIE_LOADING_CACHE</code> || Reads the complete compressed file into a shared source buffer. || Reusing a clip or avoiding repeated reads of its compressed data.
| <code>0</code>
| Exact RGB black remains unchanged.
|-
|-
| Sound channel
| <code>MOVIE_LOADING_AUTO</code> || Chooses cached or streamed storage using the engine's source-cache policy. || Automatic storage selection.
| <code>0</code>
| Embedded Vorbis audio uses conventional music and media space.
|}
|}
Cached storage contains the compressed WebM file. Each playback still owns its decoder, frame queues, position, and controls.
Automatic selection uses an aggregate movie-cache budget of one quarter of total system memory and preserves a reserve of at least one eighth of total memory or 128 MiB, whichever is greater. If a cache allocation cannot be satisfied, automatic mode can use streaming. Explicit cache mode reports a failed load. Open or size-validation failures fail loading. During caching, read errors fail the load instead of selecting streaming.


== Script playback ==
== Script playback ==
Line 191: Line 87:
=== movie_load() ===
=== movie_load() ===


Loads a reusable movie source and returns its integer source ID.
<syntaxhighlight lang="text">
movie_load(path [, loading])
</syntaxhighlight>
 
Returns an integer source ID. <code>path</code> is the exact module path; OpenBOR does not append an extension. Omitting <code>loading</code> selects <code>MOVIE_LOADING_STREAM</code>.


<syntaxhighlight lang="c" line>
<syntaxhighlight lang="c" line="1">
int source_id = movie_load(
int source_id = movie_load(
     string path,
     "data/scenes/intro.webm",
     int loading
     openborconstant("MOVIE_LOADING_AUTO")
);
);
</syntaxhighlight>
</syntaxhighlight>


{| class="wikitable"
Source ID 0 is valid. Invalid paths, empty files, invalid loading modes, and failed source allocations report script errors.
! Argument
 
! Required
=== movie_play() ===
! Default
! Description
|-
| <code>path</code>
| Yes
| None
| Exact module path to a WebM source.
|-
| <code>loading</code>
| No
| <code>MOVIE_LOADING_STREAM</code>
| <code>MOVIE_LOADING_STREAM</code>, <code>MOVIE_LOADING_CACHE</code>, or <code>MOVIE_LOADING_AUTO</code>.
|}


Invalid paths, loading modes, allocation failures, or empty cached files fail with a script error.
<syntaxhighlight lang="text">
movie_play(source_id [, movie_channel])
</syntaxhighlight>


=== movie_unload() ===
Returns the playback object for the acquired movie channel. Omit the second argument, pass <code>NULL()</code>, or use <code>MOVIE_CHANNEL_AUTO</code> for automatic selection.


Releases a loaded source.
<syntaxhighlight lang="c" line="1">
void playback = movie_play(source_id);
int channel = movie_get_channel_index(playback);


<syntaxhighlight lang="c" line>
// Select a particular movie channel.
movie_unload(int source_id);
void another_playback = movie_play(source_id, 5);
</syntaxhighlight>
</syntaxhighlight>


The source must exist and have no active playback references. Stop every playback using the source before unloading it. Unloaded IDs remain invalid and are not reassigned later in the session.
Every start restores the channel's default properties. Configure the returned playback object after calling <code>movie_play()</code>.


=== movie_play() ===
Startup is asynchronous. The channel becomes active before its first frame is necessarily ready. Drawing an active channel during startup can therefore complete without displaying a frame. Decoder-opening errors stop that playback and are reported in the engine log.


Starts a source and returns its stable movie playback object.
=== movie_stop() ===


<syntaxhighlight lang="c" line>
<syntaxhighlight lang="c">
void playback = movie_play(
movie_stop(playback);
    int source_id,
    int movie_channel
);
</syntaxhighlight>
</syntaxhighlight>


{| class="wikitable"
Stops the selected playback and makes its channel available for reuse. The channel's active state, source association, position, and duration are reset. Calling it with a valid inactive channel object leaves that channel inactive.
! Argument
! Required
! Default
! Description
|-
| <code>source_id</code>
| Yes
| None
| Source returned by <code>movie_load()</code>.
|-
| <code>movie_channel</code>
| No
| <code>MOVIE_CHANNEL_AUTO</code>
| Omit the argument or pass <code>NULL()</code> for automatic allocation. Values from <code>0</code> through <code>63</code> force that channel.
|}


Forced selection stops the current channel occupant before opening the new playback. Automatic selection never replaces an active movie and fails when no channel is free.
Decoder teardown can continue asynchronously after the channel becomes inactive. Playback objects remain owned by the engine. Creator-owned destination screens have their own lifetime and can be released with <code>free()</code> when the creator has finished using them.


Decoder opening is asynchronous. <code>movie_play()</code> returns after the channel has been acquired and playback startup has been scheduled; the first drawable frame may arrive on a later update. A decoder or track error reported afterward stops that playback and appears clearly in the engine log.
=== movie_unload() ===


The returned pointer identifies the channel object, not a permanent unique playback instance. Later forced playback on the same channel reuses the same pointer with new state.
<syntaxhighlight lang="c">
movie_unload(source_id);
</syntaxhighlight>


=== movie_stop() ===
Releases a loaded source after every playback and retiring decoder has finished using it. Invalid or still-referenced sources report a script error. This function returns no status value for polling.


Stops playback, begins decoder teardown, releases its source reference, and recycles its movie channel.
'''Source unloading requires completed decoder teardown.''' Decoder teardown may still retain that source after a channel becomes inactive. The script API has no source-readiness query; checking <code>MOVIE_PROPERTY_ACTIVE</code> alone is insufficient for an immediate unload. Keep reusable sources loaded across playbacks. Movie-system shutdown completes decoder teardown and releases remaining sources automatically.


<syntaxhighlight lang="c" line>
=== Basic screen-composition example ===
movie_stop(void playback);
</syntaxhighlight>


Calling <code>movie_stop()</code> with a valid but already inactive channel object safely leaves it inactive.
The following functions use global variables to retain the controller's state across callbacks. Call initialization once, call drawing while the interface is visible, and call cleanup when closing it. The source remains loaded for reuse.


=== Basic example ===
<syntaxhighlight lang="c" line="1">
void movie_example_init()
{
    int source_id = movie_load(
        "data/scenes/intro.webm",
        openborconstant("MOVIE_LOADING_AUTO")
    );
    void playback = movie_play(source_id);
    void screen = allocscreen(320, 180);


This example starts a movie asynchronously, draws its current frame into a creator-owned screen, adds an overlay, and submits the completed screen through the ordinary renderer.
    setglobalvar("movie_example_source", source_id);
    setglobalvar("movie_example_playback", playback);
    setglobalvar("movie_example_screen", screen);
}


Initialization:
void movie_example_draw()
{
    void playback = getglobalvar("movie_example_playback");
    void screen = getglobalvar("movie_example_screen");


<syntaxhighlight lang="c" line>
    if(playback == NULL() || screen == NULL()) return;
void movie_screen = allocscreen(360, 204);
    if(!movie_get_property(
        playback, openborconstant("MOVIE_PROPERTY_ACTIVE")
    )) return;


int source_id = movie_load(
    int channel = movie_get_channel_index(playback);
     "data/scenes/intro.webm",
    clearscreen(screen);
     openborconstant("MOVIE_LOADING_AUTO")
     movie_draw_to_screen(screen, channel);
);
     drawstringtoscreen(screen, 6, 6, 0, "PLAYING");
    drawscreen(screen, 16, 16, 5000);
}


void playback = movie_play(source_id);
void movie_example_close()
int movie_channel = movie_get_channel_index(playback);
{
</syntaxhighlight>
    void playback = getglobalvar("movie_example_playback");
    void screen = getglobalvar("movie_example_screen");


Drawing update:
    if(playback != NULL()) movie_stop(playback);
    if(screen != NULL()) free(screen);


<syntaxhighlight lang="c" line>
     setglobalvar("movie_example_playback", NULL());
if(movie_get_property(
     setglobalvar("movie_example_screen", NULL());
    playback,
     openborconstant("MOVIE_PROPERTY_ACTIVE")
))
{
    clearscreen(movie_screen);
    movie_draw_to_screen(movie_screen, movie_channel);
     drawstringtoscreen(movie_screen, 4, 4, 0, "PLAYING");
    drawscreen(movie_screen, 80, 30, 5000);
}
}
</syntaxhighlight>
</syntaxhighlight>


The source can be unloaded after playback stops:
The drawing function uses the common drawmethod when submitting its completed screen through <code>drawscreen()</code>. Keep that shared state appropriate for the intended presentation, as described in [[Drawmethod]]. Close the controller after pending draws that reference its screen have finished.
 
<syntaxhighlight lang="c" line>
if(!movie_get_property(
    playback,
    openborconstant("MOVIE_PROPERTY_ACTIVE")
))
{
    movie_unload(source_id);
}
</syntaxhighlight>


== Screen composition ==
== Screen composition ==


=== Creator-controlled drawing ===
=== movie_draw_to_screen() ===


Movie playback never stores or owns a destination screen. Call <code>movie_draw_to_screen()</code> whenever the retained frame should be copied into a screen:
<syntaxhighlight lang="text">
 
movie_draw_to_screen(screen, movie_channel)
<syntaxhighlight lang="c" line>
movie_draw_to_screen(
    void screen,
    int movie_channel
);
</syntaxhighlight>
</syntaxhighlight>


The screen must be a valid 32-bit OpenBOR screen. The second argument is the movie '''channel index''', not the playback pointer. Save the result of <code>movie_get_channel_index()</code>, read <code>MOVIE_PROPERTY_CHANNEL</code>, or use a known explicitly selected channel.
The first argument is a screen pointer. The second is an integer movie-channel index. Obtain that index with <code>movie_get_channel_index(playback)</code>, read <code>MOVIE_PROPERTY_CHANNEL</code>, or supply the channel explicitly selected at playback start.


Drawing and playback are independent:
The function draws the retained frame immediately into the selected screen. Its opaque movie rectangle is clipped to the destination, and pixels outside that rectangle retain their existing contents. Scripts control clearing, layering, later screen submission, and screen lifetime.


* Calling <code>movie_draw_to_screen()</code> does not advance the movie clock or decoder.
Use this sequence when a movie shares a composition with other graphics:
* Failing to draw does not pause playback. The movie continues in the background.
* The first few calls may draw nothing while asynchronous decoder startup or seek preroll is still in progress.
* Repeated calls copy the retained current frame. The same channel may be drawn to several screens during one update.
* OpenBOR does not clear, submit, resize, or free the destination screen.


Call <code>movie_draw_to_screen()</code> only while the channel is active. An invalid screen, inactive channel, or out-of-range channel reports a script error.
# Clear or prepare the destination.
# Draw background content.
# Draw the movie with <code>movie_draw_to_screen()</code>.
# Draw captions, sprites, or other overlays.
# Submit the completed screen with <code>drawscreen()</code>.


=== Hardware YUV presentation ===
Multiple movies drawn into one screen follow call order. Later movie rectangles replace earlier content where they overlap. Movie channel numbers do not determine that order.


Call <code>movie_draw_to_yuv()</code> to present a retained movie frame directly through the hardware YUV output path:
<code>movie_draw_to_screen()</code> uses the movie's own size, offset, resampling, and black-filter properties. Global drawmethod state does not control this operation. To rotate, curve, blend, or otherwise transform the complete movie image, draw it into a subscreen and apply [[Drawmethod]] settings when drawing that screen.


<syntaxhighlight lang="c" line>
=== Main screen and subscreens ===
movie_draw_to_yuv(int movie_channel);
</syntaxhighlight>


The argument is the movie channel index, not the playback pointer. Save the result of <code>movie_get_channel_index()</code>, read <code>MOVIE_PROPERTY_CHANNEL</code>, or use a known explicitly selected channel.
Use <code>allocscreen(width, height)</code> to create a subscreen. For a drawing hook that operates directly on the main virtual screen:


Hardware YUV presentation bypasses software conversion to a 32-bit OpenBOR screen. SDL renderer builds upload the Y, U, and V planes to a streaming YUV texture. OpenGL builds upload the planes independently and perform YUV-to-RGB conversion in the fragment shader.
<syntaxhighlight lang="c">
void destination = openborvariant("vscreen");
movie_draw_to_screen(destination, channel);
</syntaxhighlight>


Calling <code>movie_draw_to_yuv()</code> does not advance playback. Call it whenever a newly retained frame should be presented. Calls made before the first decoded frame becomes available succeed without displaying anything.
Direct main-screen drawing participates at the point where the script executes. Subsequent drawing can cover it, and a subsequent clear removes it. Playback retains no destination pointer, so each call can select a different screen.


The hardware path is an '''exclusive final-output operation'''. It replaces the normal game output texture for the duration of YUV presentation and presents directly to the display. Consequently:
Both drawing functions require an active channel. Before the first frame is ready, a valid draw can do nothing successfully. Invalid channels, inactive channels, invalid screen destinations, and failed rendering report script errors. The drawing functions return no script value.


* It does not accept an <code>s_screen</code> destination.
=== Dimensions and offsets ===
* It cannot draw into a subscreen.
* It does not participate in sprite or screen composition order.
* It cannot layer text, sprites, boxes, or effects over the movie.
* <code>MOVIE_PROPERTY_OFFSET_X</code> and <code>MOVIE_PROPERTY_OFFSET_Y</code> do not apply.
* <code>MOVIE_PROPERTY_BLACK_FILTER</code> does not apply.
* Only one movie channel can occupy the hardware output at a time.
* Stopping or completing the YUV-presented movie restores the configured OpenBOR video mode automatically.


Playback controls remain fully available because they belong to the movie channel rather than the presentation path. Scripts may pause, resume, seek, change speed, enable repeat, read position, change sound routing, or stop a movie presented through hardware YUV.
Width and height resolve independently:


=== Hardware YUV sizing ===
{| class="wikitable"
! Property value !! Screen composition !! Direct display
|-
| <code>0</code> || Use the corresponding destination-screen dimension. || Use the corresponding WebM display dimension.
|-
| <code>MOVIE_SIZE_NATIVE</code> || Use the corresponding decoded-frame dimension. || Use the corresponding WebM display dimension.
|-
| Positive explicit value || Set the movie rectangle's dimension in destination pixels. || Set the requested logical display dimension.
|}


<code>MOVIE_PROPERTY_WIDTH</code> and <code>MOVIE_PROPERTY_HEIGHT</code> also select the logical display dimensions used by hardware YUV presentation.
Set <code>MOVIE_PROPERTY_OFFSET_X</code> and <code>MOVIE_PROPERTY_OFFSET_Y</code> to place the movie rectangle within a screen. Offsets are signed. Oversized dimensions combined with negative offsets provide zoom-and-crop layouts; smaller dimensions provide inset placement. Set both dimensions appropriately when preserving the movie's aspect ratio.


* Zero uses the corresponding WebM display dimension.
For a 640 by 360 movie rectangle centered within a 320 by 180 subscreen:
* <code>MOVIE_SIZE_NATIVE</code> also uses the WebM display dimension.
* Other positive values request that display dimension explicitly.
* Width and height remain independent, so creators may intentionally change the aspect ratio.


The decoded YUV texture retains the source frame dimensions. Width and height control its displayed size rather than forcing an intermediate software RGB conversion.
<syntaxhighlight lang="c" line="1">
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_WIDTH"), 640);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_HEIGHT"), 360);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_OFFSET_X"), -160);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_OFFSET_Y"), -90);


=== Hardware YUV example ===
movie_draw_to_screen(movie_screen, channel);
</syntaxhighlight>


<syntaxhighlight lang="c" line>
With width and height both zero, the same playback can fill destinations of different sizes:
int source_id = movie_load(
    "data/scenes/intro.webm",
    openborconstant("MOVIE_LOADING_STREAM")
);
 
void playback = movie_play(source_id);
int channel = movie_get_channel_index(playback);
 
movie_set_property(
    playback,
    openborconstant("MOVIE_PROPERTY_WIDTH"),
    openborconstant("MOVIE_SIZE_NATIVE")
);


movie_set_property(
<syntaxhighlight lang="c" line="1">
    playback,
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_WIDTH"), 0);
    openborconstant("MOVIE_PROPERTY_HEIGHT"),
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_HEIGHT"), 0);
    openborconstant("MOVIE_SIZE_NATIVE")
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_OFFSET_X"), 0);
);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_OFFSET_Y"), 0);


// Call during the drawing update while playback is active.
movie_draw_to_screen(large_screen, channel);
movie_draw_to_yuv(channel);
movie_draw_to_screen(small_screen, channel);
</syntaxhighlight>
</syntaxhighlight>


Pause, seek, speed, and stop controls use the same playback object:
Both calls draw the same retained frame. Changing dimensions or offsets changes its presentation without restarting playback.


<syntaxhighlight lang="c" line>
=== Exact-black protection ===
movie_set_property(
    playback,
    openborconstant("MOVIE_PROPERTY_PAUSED"),
    1
);


movie_set_property(
Screen transparency settings can use RGB <code>0, 0, 0</code> as a transparent key when a subscreen is drawn later. Enable black protection when the movie's black areas should remain visible through such a composition:
    playback,
    openborconstant("MOVIE_PROPERTY_POSITION"),
    30000
);


<syntaxhighlight lang="c">
movie_set_property(
movie_set_property(
     playback,
     playback, openborconstant("MOVIE_PROPERTY_BLACK_FILTER"), 1
    openborconstant("MOVIE_PROPERTY_PAUSED"),
    0
);
);
// Later:
movie_stop(playback);
</syntaxhighlight>
</syntaxhighlight>


=== Drawing order ===
The GPU first resamples the video planes and converts the result to RGB. It then changes exact output black to RGB <code>1, 1, 1</code> when protection is enabled. Other output colors retain their values. This protection is disabled by default and applies to screen composition.


The location of <code>movie_draw_to_screen()</code> in creator code determines composition order. Nothing is injected automatically before or after the sprite queue.
== Movie resampling ==


For a typical creator-owned subscreen:
<code>MOVIE_PROPERTY_RESAMPLE</code> selects the filter used when rendering the decoded video. It applies to screen composition and direct display.


# Clear or prepare the destination screen.
{| class="wikitable"
# Draw any background content that belongs below the movie.
! Constant !! Sampling
# Call <code>movie_draw_to_screen()</code>.
|-
# Draw text, sprites, boxes, or effects that belong over the movie.
| <code>DC_RESAMPLE_MOVIE</code> || Movie default; equivalent to bilinear.
# Submit the completed screen with <code>drawscreen()</code>.
|-
 
| <code>DC_RESAMPLE_NEAREST</code> || Nearest-sample reconstruction.
Calling two movie channels against the same screen follows normal call order. The second call overwrites the first where their destination rectangles overlap. This makes layering explicit and independent of channel numbers.
|-
 
| <code>DC_RESAMPLE_BILINEAR</code> || Linear reconstruction between neighboring samples.
The destination's normal <code>drawscreen()</code> drawmethod remains available for whole-screen rotation, scaling, flipping, blending, or other later composition.
|-
 
| <code>DC_RESAMPLE_BICUBIC_CATMULL_ROM</code> || Catmull-Rom cubic reconstruction.
=== Main screen and subscreens ===
|-
 
| <code>DC_RESAMPLE_BICUBIC_MITCHELL</code> || Mitchell cubic reconstruction.
Use <code>[[Allocscreen()|allocscreen(width, height)]]</code> for a creator-owned 32-bit subscreen. Use <code>[[openborvariant("vscreen")]]</code> when a suitable drawing hook must address the engine's main screen directly:
|-
 
| <code>DC_RESAMPLE_BICUBIC_BSPLINE</code> || B-spline cubic reconstruction.
<syntaxhighlight lang="c" line>
|-
void main_screen = openborvariant("vscreen");
| <code>DC_RESAMPLE_LANCZOS_2</code> || Two-lobe Lanczos reconstruction.
movie_draw_to_screen(main_screen, movie_channel);
|-
</syntaxhighlight>
| <code>DC_RESAMPLE_LANCZOS_3</code> || Three-lobe Lanczos reconstruction.
 
|}
Direct main-screen drawing follows the same rule as every other screen operation: later engine or script drawing may cover it, and a later clear erases it. A subscreen usually provides the most predictable choice when a movie is part of a larger creator-controlled layout.
 
Changing destinations only means passing a different screen to the next draw call. Playback keeps no screen pointer between calls.
 
=== Width, height, offsets, and clipping ===
 
<code>MOVIE_PROPERTY_WIDTH</code> and <code>MOVIE_PROPERTY_HEIGHT</code> independently select the prepared frame dimensions.
 
* Zero width uses the destination screen width at draw time.
* Zero height uses the destination screen height at draw time.
* <code>MOVIE_SIZE_NATIVE</code> uses the decoded video's native dimension.
* Other positive values scale the decoded frame to the requested dimension.
* Width and height may be set independently, so scripts are responsible for preserving aspect ratio when desired.
 
<code>MOVIE_PROPERTY_OFFSET_X</code> and <code>MOVIE_PROPERTY_OFFSET_Y</code> place the scaled frame inside the destination. Offsets are signed. Pixels outside the destination are clipped safely.
 
Scaling a movie larger than its destination and applying negative offsets provides a controllable zoom-and-crop effect. Scaling it smaller provides picture-in-picture placement.
 
These composition rules describe <code>movie_draw_to_screen()</code>. Hardware YUV presentation does not have a destination screen. Its width and height select the logical display dimensions, while offsets, clipping, and black filtering do not apply.
 
=== Zoom-and-crop example ===
 
This example prepares a 320 by 180 movie image and clips its central 160 by 90 region into a subscreen.
 
<syntaxhighlight lang="c" line>
void screen = allocscreen(160, 90);
int source_id = movie_load("data/scenes/camera.webm");
void playback = movie_play(source_id);
int channel = movie_get_channel_index(playback);
 
movie_set_property(
    playback,
    openborconstant("MOVIE_PROPERTY_WIDTH"),
    320
);


<syntaxhighlight lang="c" line="1">
movie_set_property(
movie_set_property(
     playback,
     playback,
     openborconstant("MOVIE_PROPERTY_HEIGHT"),
     openborconstant("MOVIE_PROPERTY_RESAMPLE"),
     180
     openborconstant("DC_RESAMPLE_BICUBIC_MITCHELL")
);
);


movie_set_property(
int filter = movie_get_property(
     playback,
     playback, openborconstant("MOVIE_PROPERTY_RESAMPLE")
    openborconstant("MOVIE_PROPERTY_OFFSET_X"),
    -80
);
);
movie_set_property(
    playback,
    openborconstant("MOVIE_PROPERTY_OFFSET_Y"),
    -45
);
clearscreen(screen);
movie_draw_to_screen(screen, channel);
drawscreen(screen, 80, 30, 5000);
</syntaxhighlight>
</syntaxhighlight>


=== Multiple destinations example ===
The GPU reconstructs the Y, U, and V planes at their respective resolutions before converting to RGB. Changing this property takes effect when the frame is drawn again, including while playback is paused. It does not seek or restart decoding.


One playback may feed several compositions without additional decoding. This example draws the same retained frame full-size into one screen and again into a smaller screen whose dimensions are selected by the playback properties.
Movie resampling controls video-to-destination rendering. Drawmethod resampling can separately control a subsequent transformed <code>drawscreen()</code> operation. Final display filtering is another stage applied when presenting the completed game screen. See [[Drawmethod#Resampling|Drawmethod resampling]].


<syntaxhighlight lang="c" line>
== Direct display presentation ==
movie_set_property(
    playback,
    openborconstant("MOVIE_PROPERTY_WIDTH"),
    0
);


movie_set_property(
=== movie_draw_to_yuv() ===
    playback,
    openborconstant("MOVIE_PROPERTY_HEIGHT"),
    0
);


movie_draw_to_screen(large_screen, movie_channel);
<syntaxhighlight lang="c">
movie_draw_to_screen(small_screen, movie_channel);
movie_draw_to_yuv(channel);
</syntaxhighlight>
</syntaxhighlight>


Zero dimensions are resolved separately for each destination. Both calls use the same decoded current frame.
This function renders the retained movie frame directly to the display window and presents it immediately. It clears the window background, centers the movie using the selected logical display dimensions, and applies display brightness and gamma. The display's stretch setting can fill the window.
 
Logical display dimensions are scaled for the actual window. They are independent of the game screen resolution configured in <code>video.txt</code>; explicit movie width and height are not literal window-pixel extents. Movie X/Y offsets and exact-black protection are screen-composition controls and do not apply here.


=== Exact-black protection ===
Each direct-display call presents a complete movie view. Use screen composition to assemble captions, sprites, several movies, or other overlays into one frame. Direct presentation preserves the normal graphics resources, so ordinary screen rendering and presentation remain available. Stopping a directly presented movie clears its direct-presentation state.


Some subscreen composition paths treat RGB <code>0, 0, 0</code> as a transparency mask. Enable <code>MOVIE_PROPERTY_BLACK_FILTER</code> to protect exact-black movie pixels:
For example, after acquiring an active playback:


<syntaxhighlight lang="c" line>
<syntaxhighlight lang="c" line="1">
movie_set_property(
movie_set_property(
     playback,
     playback, openborconstant("MOVIE_PROPERTY_WIDTH"),
     openborconstant("MOVIE_PROPERTY_BLACK_FILTER"),
     openborconstant("MOVIE_SIZE_NATIVE")
     1
);
movie_set_property(
    playback, openborconstant("MOVIE_PROPERTY_HEIGHT"),
     openborconstant("MOVIE_SIZE_NATIVE")
);
);
// Call when the controller wants to present the retained movie frame.
if(movie_get_property(playback, openborconstant("MOVIE_PROPERTY_ACTIVE")))
{
    movie_draw_to_yuv(movie_get_channel_index(playback));
}
</syntaxhighlight>
</syntaxhighlight>


When enabled, OpenBOR changes only exact RGB <code>0, 0, 0</code> movie pixels to RGB <code>1, 1, 1</code> after YUV conversion. Other near-black shades remain unchanged. The filter affects the prepared movie frame before scaling and composition.
Position, pause, speed, repeat, interruption, and sound routing use the same playback properties for either destination.
 
The filter is disabled by default because not every composition path uses exact black as transparency.


== Playback timing and control ==
== Playback timing and control ==


Movie control is provided through the property API. Timing properties use milliseconds. Playback controls belong to the movie channel and work with both <code>movie_draw_to_screen()</code> and <code>movie_draw_to_yuv()</code>.
Position and duration use milliseconds. The playback clock begins when asynchronous decoder startup is ready. Drawing does not move the clock, and omitting drawing does not pause the movie.


Embedded audio owns the master playback clock when an audio track is present. Video presentation follows that clock, and sufficiently late decoded frames may be discarded to preserve synchronization. Video-only sources use the movie playback clock directly. Drawing is still creator-controlled and does not change either clock.
While the movie owns an embedded audio stream, consumed audio provides the playback clock. Video follows that clock, with late frames discarded when necessary to preserve synchronization. Video-only playback uses the movie's own clock. If another audio producer replaces the movie's sound stream, the movie continues from a matching position on its own clock.


=== Position and seeking ===
=== Position and seeking ===


<code>MOVIE_PROPERTY_POSITION</code> reports the current playback position as an unsigned 64-bit millisecond value. Writing it schedules an asynchronous seek and decoder reopen at the requested position.
Read <code>MOVIE_PROPERTY_POSITION</code> for the playback position. Write it to request a seek:


<code>MOVIE_PROPERTY_DURATION</code> reports the source duration in milliseconds and is read-only. Seeking at or beyond a known duration clamps the request to the final available millisecond.
<syntaxhighlight lang="c">
 
movie_set_property(
<syntaxhighlight lang="c" line>
    playback, openborconstant("MOVIE_PROPERTY_POSITION"), 12500
int position_id = openborconstant("MOVIE_PROPERTY_POSITION");
);
 
movie_set_property(playback, position_id, 30000); // 30 seconds
</syntaxhighlight>
</syntaxhighlight>


Seeking preserves the last prepared frame until a replacement frame is ready. Streamed seek latency depends on storage performance and WebM keyframe placement. Cached mode can reduce storage latency but still performs decoder work.
This requests 12.5 seconds. Seeking reopens decoding asynchronously while retaining the displayed frame until replacement frames are ready. When duration is known, a seek at or beyond its end is clamped to the last available millisecond. <code>MOVIE_PROPERTY_DURATION</code> is read-only and remains zero until duration is known.


Seeking is also the intended way to move backward. Reverse playback is not supported.
Use position changes for rewind controls and other backward navigation. Continuous negative-speed playback is not supported.


=== Pause ===
=== Pause ===


<code>MOVIE_PROPERTY_PAUSED</code> accepts zero or nonzero values. Pausing freezes the movie clock, preserves the current frame, and pauses embedded audio. Resuming continues from the stored position.
Set <code>MOVIE_PROPERTY_PAUSED</code> to 1 to hold the position and displayed frame and pause the movie's audio. Set it to 0 to resume.


=== Speed and fast-forward ===
<syntaxhighlight lang="c">
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_PAUSED"), 1);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_PAUSED"), 0);
</syntaxhighlight>


<code>MOVIE_PROPERTY_SPEED</code> accepts a decimal from <code>0.0</code> through <code>16.0</code>. Negative values are rejected.
=== Speed ===


{| class="wikitable"
<code>MOVIE_PROPERTY_SPEED</code> accepts finite nonnegative values. Normal speed is <code>1.0</code>. Values below 1 slow playback; values above 1 accelerate it. Positive speed changes also change embedded-audio speed and pitch.
! Speed
! Video behavior
! Embedded-audio behavior
|-
| <code>1.0</code>
| Normal forward playback.
| Normal speed and pitch.
|-
| Greater than <code>1.0</code>
| Fast-forward.
| Speed and pitch increase with the positive rate.
|-
| Between <code>0.0</code> and <code>1.0</code>
| Slow forward playback.
| Speed and pitch decrease with the positive rate.
|-
| <code>0.0</code>
| Holds the current position and frame.
| Paused.
|}


<syntaxhighlight lang="c" line>
Rates above <code>16.0</code> are clamped to 16.0, and accepted rates are rounded to the nearest 0.001. Negative or nonfinite values report an error. Zero holds the position and pauses audio. Returning from zero to a positive rate reopens decoding at the held position.
int speed_id = openborconstant("MOVIE_PROPERTY_SPEED");


movie_set_property(playback, speed_id, 2.0); // Fast-forward
<syntaxhighlight lang="c" line="1">
movie_set_property(playback, speed_id, 1.0); // Normal
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_SPEED"), 0.5);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_SPEED"), 2.0);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_SPEED"), 1.0);
</syntaxhighlight>
</syntaxhighlight>


Use <code>MOVIE_PROPERTY_POSITION</code> for rewind controls or other backward navigation.
These statements select half speed, double speed, and normal speed respectively; use the statement matching the desired control action.


=== Repeat ===
=== Repeat and interruption ===


<code>MOVIE_PROPERTY_REPEAT</code> accepts zero or nonzero values. Playback reopens at the beginning after its terminal frame.
Set <code>MOVIE_PROPERTY_REPEAT</code> to 1 to reopen playback from the beginning when it reaches its terminal frame. Scripts can implement a custom loop region by observing position and requesting a seek to its beginning.


Movie playback has no separate repeat offset. Scripts can implement custom loop regions by observing position and writing a new position.
<code>MOVIE_PROPERTY_INTERRUPT</code> defaults to 1. New Escape or normal movie-skip input stops interruptible playback during the engine update. Set it to 0 when a controller should handle stopping itself:


=== Input interruption ===
<syntaxhighlight lang="c" line="1">
 
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_REPEAT"), 1);
<code>MOVIE_PROPERTY_INTERRUPT</code> defaults to <code>1</code>. New Escape or normal movie-skip button presses stop playback during the engine update.
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_INTERRUPT"), 0);
 
Set the property to <code>0</code> when playback must continue until natural completion or an explicit <code>movie_stop()</code> call:
 
<syntaxhighlight lang="c" line>
movie_set_property(
    playback,
    openborconstant("MOVIE_PROPERTY_INTERRUPT"),
    0
);
</syntaxhighlight>
</syntaxhighlight>


== Embedded audio ==
== Embedded audio ==


Movie channels and sound channels are independent address spaces.
Movie channels select playback objects. Sound channels select destinations in the audio mixer. Their indexes are separate: movie channels run from 0 through 63, and sound channels run from 0 through 4095.
 
* Movie channels range from <code>0</code> through <code>63</code> and own video playback objects.
* Sound channels range from <code>0</code> through <code>4095</code> and mix audio.
* Every new movie playback initially routes embedded audio to sound channel <code>0</code>.
* Modern <code>movie_play()</code> playback replaces only its selected sound channel. It does not stop unrelated sound channels.
* WebM sources without an audio track leave existing sound playback unchanged.
* Failure to open an otherwise optional audio track leaves the video playing silently and reports the failure in the log.


Channel <code>0</code> is OpenBOR's soft-reserved music and media channel. Starting a movie with embedded audio therefore replaces the current occupant of sound channel 0 unless the movie has already been routed elsewhere.
Each playback initially selects sound channel 0, the music and media channel. Embedded audio replaces the occupant of its selected sound channel. Ordinary <code>movie_play()</code> leaves unrelated sound channels running, and a movie without audio leaves existing sound playback alone.


=== movie_set_sound_channel() ===
=== movie_set_sound_channel() ===


Moves a playback's embedded audio to an explicit sound channel.
<syntaxhighlight lang="text">
 
movie_set_sound_channel(playback, sound_channel)
<syntaxhighlight lang="c" line>
movie_set_sound_channel(
    void playback,
    int sound_channel
);
</syntaxhighlight>
</syntaxhighlight>


Valid sound channels are <code>0</code> through <code>4095</code>. Changing the sound channel schedules a decoder reopen at the current movie position so video and audio remain synchronized. The selected sound channel is forced: an existing occupant is replaced without a priority check.
Routes an active playback's embedded audio to the selected sound channel. Changing the destination reopens decoding asynchronously at the playback position. Selecting the already assigned channel leaves its routing in place. The destination is selected directly, so its existing audio is replaced without priority arbitration.
 
The sound-channel property is read-only through <code>movie_set_property()</code>. Use <code>movie_set_sound_channel()</code> to change routing.


Route each movie to its intended sound channel immediately after starting it and before starting the next audible movie:
For simultaneous audible movies, assign separate sound channels immediately after starting each playback:


<syntaxhighlight lang="c" line>
<syntaxhighlight lang="c" line="1">
int source_a = movie_load("data/scenes/feed_a.webm");
int source_a = movie_load("data/scenes/feed_a.webm");
int source_b = movie_load("data/scenes/feed_b.webm");
int source_b = movie_load("data/scenes/feed_b.webm");


void movie_a = movie_play(source_a, 4);
void playback_a = movie_play(source_a, 4);
movie_set_sound_channel(movie_a, 10);
movie_set_sound_channel(playback_a, 10);


void movie_b = movie_play(source_b, 5);
void playback_b = movie_play(source_b, 5);
movie_set_sound_channel(movie_b, 11);
movie_set_sound_channel(playback_b, 11);
</syntaxhighlight>
</syntaxhighlight>


The embedded streams are ordinary producer-fed sound objects. Scripts may inspect their volume, pause state, play ID, and other applicable common properties through the [[Audio Overview|sound object API]]. Sample-backed seeking properties do not apply to producer-fed movie audio; seek through <code>MOVIE_PROPERTY_POSITION</code> instead.
<code>MOVIE_PROPERTY_SOUND_CHANNEL</code> reports this routing and is read-only through the property API. Embedded streams also expose applicable controls through the sound-object API. Seek the movie through <code>MOVIE_PROPERTY_POSITION</code> so audio and video remain coordinated. See [[Audio Overview]].


== Movie object script API ==
== Movie object API ==


Advanced scripts may inspect the fixed movie channel bank, obtain stable channel objects, and read or change playback properties.
Use <code>openborconstant()</code> for property and loading-mode names. Channel indexes are ordinary integers.


Use named constants from <code>openborconstant()</code>. Raw numeric property and mode IDs are implementation details.
=== Channel access ===


=== movie_get_channel_mask() ===
{| class="wikitable"
! Function !! Result
|-
| <code>movie_get_channel_object(channel)</code> || Engine-owned object for that channel, including an inactive channel.
|-
| <code>movie_get_channel_index(playback)</code> || Index belonging to a valid playback object.
|-
| <code>movie_get_channel_mask()</code> || Unsigned 64-bit activity mask with one bit per movie channel. Set bits identify active playback on their corresponding channels.
|}


<syntaxhighlight lang="c" line>
For a particular channel, read its active state directly:
mixed active_mask = movie_get_channel_mask();
</syntaxhighlight>


Returns an unsigned 64-bit mask. Bit <code>0</code> represents movie channel 0, bit <code>1</code> represents channel 1, and so on. Set bits indicate active playback.
<syntaxhighlight lang="c" line="1">
 
void playback = movie_get_channel_object(5);
=== movie_get_channel_object() ===
int active = movie_get_property(
 
    playback, openborconstant("MOVIE_PROPERTY_ACTIVE")
<syntaxhighlight lang="c" line>
);
void playback = movie_get_channel_object(int movie_channel);
</syntaxhighlight>
</syntaxhighlight>


Returns the stable movie object for a channel from <code>0</code> through <code>63</code>. The fixed bank exists after movie-system initialization, so inactive channels still return objects. Test <code>MOVIE_PROPERTY_ACTIVE</code> or the active mask before treating the object as current playback.
=== Property access ===
 
=== movie_get_channel_index() ===


<syntaxhighlight lang="c" line>
<syntaxhighlight lang="text">
int movie_channel = movie_get_channel_index(void playback);
movie_get_property(playback, property)
movie_set_property(playback, property, value)
</syntaxhighlight>
</syntaxhighlight>


Validates a movie object pointer and returns its channel index.
The getter returns the property's value. The setter returns no value. Invalid objects, property identifiers, values, and writes to read-only properties report script errors.
 
=== Property access ===


<syntaxhighlight lang="c" line>
The following defaults describe a newly started playback. Stopping resets the channel; its source becomes invalid and position and duration become zero.
mixed value = movie_get_property(
    void playback,
    int property
);
 
movie_set_property(
    void playback,
    int property,
    mixed value
);
</syntaxhighlight>
 
Property reads use a synchronized public-state snapshot. Playback-sensitive writes route through lifecycle-aware helpers so clocks, decoders, frame scaling, and audio remain coherent.


{| class="wikitable"
{| class="wikitable"
! Property constant
! Property !! Access !! Default !! Meaning
! Type
! Access
! Default
! Description
|-
|-
| <code>MOVIE_PROPERTY_ACTIVE</code>
| <code>MOVIE_PROPERTY_ACTIVE</code> || Read || 1 after start || Whether the channel owns active playback.
| Integer
| Read
| <code>0</code> before play
| <code>1</code> while the channel owns active playback; otherwise <code>0</code>.
|-
|-
| <code>MOVIE_PROPERTY_BLACK_FILTER</code>
| <code>MOVIE_PROPERTY_BLACK_FILTER</code> || Read/write || 0 || Protect exact output black during screen composition.
| Integer
| Read/write
| <code>0</code>
| Converts exact RGB black movie pixels to RGB <code>1, 1, 1</code>.
|-
|-
| <code>MOVIE_PROPERTY_CHANNEL</code>
| <code>MOVIE_PROPERTY_CHANNEL</code> || Read || Acquired index || Movie channel index.
| Integer
| Read
| Channel index
| Stable movie channel from <code>0</code> through <code>63</code>.
|-
|-
| <code>MOVIE_PROPERTY_DURATION</code>
| <code>MOVIE_PROPERTY_DURATION</code> || Read || 0 until known || Unsigned 64-bit duration in milliseconds.
| Unsigned 64-bit integer
| Read
| Source value
| Duration in milliseconds.
|-
|-
| <code>MOVIE_PROPERTY_HEIGHT</code>
| <code>MOVIE_PROPERTY_HEIGHT</code> || Read/write || 0 || Height selection; see [[#Dimensions and offsets|Dimensions and offsets]].
| Unsigned 64-bit integer
| Read/write
| <code>0</code>
| Prepared frame height. Zero uses destination height; <code>MOVIE_SIZE_NATIVE</code> uses native video height.
|-
|-
| <code>MOVIE_PROPERTY_INTERRUPT</code>
| <code>MOVIE_PROPERTY_INTERRUPT</code> || Read/write || 1 || Allow normal movie-skip input.
| Integer
| Read/write
| <code>1</code>
| Nonzero allows normal movie-skip input to stop playback.
|-
|-
| <code>MOVIE_PROPERTY_OFFSET_X</code>
| <code>MOVIE_PROPERTY_OFFSET_X</code> || Read/write || 0 || Signed horizontal placement within a destination screen.
| Integer
| Read/write
| <code>0</code>
| Signed horizontal destination offset. Overflow is clipped.
|-
|-
| <code>MOVIE_PROPERTY_OFFSET_Y</code>
| <code>MOVIE_PROPERTY_OFFSET_Y</code> || Read/write || 0 || Signed vertical placement within a destination screen.
| Integer
| Read/write
| <code>0</code>
| Signed vertical destination offset. Overflow is clipped.
|-
|-
| <code>MOVIE_PROPERTY_PAUSED</code>
| <code>MOVIE_PROPERTY_PAUSED</code> || Read/write || 0 || Hold the playback clock and owned audio stream.
| Integer
| Read/write
| <code>0</code>
| Pause state. Writes require active playback.
|-
|-
| <code>MOVIE_PROPERTY_POSITION</code>
| <code>MOVIE_PROPERTY_POSITION</code> || Read/write || 0 || Unsigned 64-bit millisecond position. Writing requests a seek.
| Unsigned 64-bit integer
| Read/write
| <code>0</code>
| Current millisecond position. Writing seeks active playback.
|-
|-
| <code>MOVIE_PROPERTY_REPEAT</code>
| <code>MOVIE_PROPERTY_REPEAT</code> || Read/write || 0 || Restart from the beginning at the terminal frame.
| Integer
| Read/write
| <code>0</code>
| Nonzero repeats at the source boundary.
|-
|-
| <code>MOVIE_PROPERTY_SOUND_CHANNEL</code>
| <code>MOVIE_PROPERTY_RESAMPLE</code> || Read/write || <code>DC_RESAMPLE_MOVIE</code> || Filter used to render decoded video; the movie default is bilinear.
| Integer
| Read
| <code>0</code>
| Generic sound channel used by embedded audio. Change with <code>movie_set_sound_channel()</code>.
|-
|-
| <code>MOVIE_PROPERTY_SOURCE</code>
| <code>MOVIE_PROPERTY_SOUND_CHANNEL</code> || Read || 0 || Embedded-audio destination. Change with <code>movie_set_sound_channel()</code>.
| Integer
| Read
| <code>-1</code> while inactive
| Source ID owned by the current playback.
|-
|-
| <code>MOVIE_PROPERTY_SPEED</code>
| <code>MOVIE_PROPERTY_SOURCE</code> || Read || Played source || Source ID associated with playback.
| Decimal
| Read/write
| <code>1.0</code>
| Forward playback speed from <code>0.0</code> through <code>16.0</code>.
|-
|-
| <code>MOVIE_PROPERTY_WIDTH</code>
| <code>MOVIE_PROPERTY_SPEED</code> || Read/write || 1.0 || Forward playback rate, normalized to 0 through 16.
| Unsigned 64-bit integer
|-
| Read/write
| <code>MOVIE_PROPERTY_WIDTH</code> || Read/write || 0 || Width selection; see [[#Dimensions and offsets|Dimensions and offsets]].
| <code>0</code>
| Prepared frame width. Zero uses destination width; <code>MOVIE_SIZE_NATIVE</code> uses native video width.
|}
|}


=== Property example ===
Boolean properties use zero for disabled and nonzero for enabled. Pause, position, speed, and sound-routing changes require active playback. Configure appearance, repeat, and interruption after starting playback because each start restores the defaults.


This example pauses an active playback, seeks to 12.5 seconds, disables skip input, and resumes at half speed.
For a diagnostic listing of the public property map:


<syntaxhighlight lang="c" line>
<syntaxhighlight lang="c">
if(movie_get_property(
movie_get_property(playback, openborconstant("PROPERTY_ACCESS_DUMP"));
    playback,
</syntaxhighlight>
    openborconstant("MOVIE_PROPERTY_ACTIVE")
))
{
    movie_set_property(
        playback,
        openborconstant("MOVIE_PROPERTY_PAUSED"),
        1
    );
 
    movie_set_property(
        playback,
        openborconstant("MOVIE_PROPERTY_POSITION"),
        12500
    );


    movie_set_property(
This writes the property listing to the engine log.
        playback,
        openborconstant("MOVIE_PROPERTY_INTERRUPT"),
        0
    );


    movie_set_property(
== Blocking playback ==
        playback,
        openborconstant("MOVIE_PROPERTY_SPEED"),
        0.5
    );


    movie_set_property(
Use blocking playback when a movie should complete or be interrupted before its calling script or scene continues.
        playback,
        openborconstant("MOVIE_PROPERTY_PAUSED"),
        0
    );
}
</syntaxhighlight>
 
== Legacy playback ==
 
Traditional WebM entry points remain available as wrappers around the movie system. Their defaults intentionally reproduce historical blocking fullscreen behavior.


=== playwebm() ===
=== playwebm() ===


<syntaxhighlight lang="c" line>
<syntaxhighlight lang="text">
int result = playwebm(
playwebm(path [, noskip])
    string path,
    int noskip
);
</syntaxhighlight>
</syntaxhighlight>


{| class="wikitable"
<syntaxhighlight lang="c">
! Argument
int result = playwebm("data/scenes/intro.webm", 0);
! Required
</syntaxhighlight>
! Default
! Description
|-
| <code>path</code>
| Yes
| None
| Exact WebM source path.
|-
| <code>noskip</code>
| No
| <code>0</code>
| Zero permits normal skip input. Nonzero forces playback to continue until completion or error.
|}


Return values:
<code>noskip</code> defaults to 0, allowing normal skip input. Nonzero disables that input interruption.


{| class="wikitable"
{| class="wikitable"
! Result
! Result !! Meaning
! Meaning
|-
|-
| <code>1</code>
| <code>1</code> || Movie completed.
| Playback completed normally.
|-
|-
| <code>0</code>
| <code>0</code> || Playback failed.
| Loading, decoding, rendering, or cleanup failed.
|-
|-
| <code>-1</code>
| <code>-1</code> || Permitted input interrupted playback.
| Creator-enabled input interrupted playback.
|}
|}


The wrapper performs the following operations:
The function stops existing movie playbacks, opens a streamed source, and presents it directly using the WebM display dimensions. It services input and movie playback while blocking the caller. Width and height use <code>MOVIE_SIZE_NATIVE</code>, playback speed is normal, repeat is disabled, and movie resampling uses its bilinear default.


* Stops every active movie playback.
Movies with embedded audio request exclusive audio playback through sound channel 0. Silent movies allow existing music to continue. Screenshot capture renders the movie through the GPU into a capture screen before reading the completed pixels for the screenshot.
* Loads the requested source in streamed mode.
* Uses automatic movie-channel selection.
* Uses normal speed, no repeat, and sound channel 0.
* Sets width and height to <code>MOVIE_SIZE_NATIVE</code>.
* Blocks the calling scene or script until completion, interruption, or error.
* Presents each available frame through the hardware YUV output path.
* Uses the WebM display dimensions instead of scaling through the resolution configured by <code>video.txt</code>.
* Captures screenshots from a native-resolution 32-bit conversion of the current YUV frame.
* Restores the configured OpenBOR video mode when playback ends.
* Unloads its temporary source before returning.
* Preserves the historical replace-all sound behavior when the WebM contains audio.


Legacy WebM files with embedded audio stop current music and active sample playback before opening a producer-fed stream on sound channel 0. Legacy WebM files without audio leave existing channel 0 playback running.
Cleanup completes decoder teardown and releases the temporary source before returning. Normal game rendering remains available after direct movie presentation.


=== Scene video command ===
=== Scene video command ===


Scene files retain their existing command:
<syntaxhighlight lang="text">
video path [skipone] [noskip]
</syntaxhighlight>
 
Both optional flags default to zero.


<syntaxhighlight lang="c" line>
{| class="wikitable"
video {path} {skipone} {noskip}
! Setting !! Behavior
</syntaxhighlight>
|-
| <code>skipone 0</code> || Interrupting a video skips the remaining scene media.
|-
| <code>skipone 1</code> || Interrupting a video skips it and continues with subsequent scene commands.
|-
| <code>noskip 0</code> || Normal movie-skip input is allowed.
|-
| <code>noskip 1</code> || Movie-skip input is disabled.
|}


<code>noskip</code> uses the same interruption rule as <code>playwebm()</code>. When interruption is enabled, <code>skipone</code> controls whether an interrupted video allows the scene parser to continue instead of closing the remaining scene.
For example, allow skipping just this video while continuing the scene:


Projects requiring asynchronous playback, seeking, speed control, repeat, caching, multiple movie channels, or separate sound routing should use the <code>movie_*</code> API. Use <code>movie_draw_to_screen()</code> when the movie must participate in normal screen composition. Use <code>movie_draw_to_yuv()</code> for exclusive hardware-accelerated presentation. Traditional <code>playwebm()</code> and the scene <code>video</code> command remain appropriate for intentionally blocking, native-size hardware YUV playback.
<syntaxhighlight lang="text">
video data/scenes/intro.webm 1 0
</syntaxhighlight>


== Practical guidance ==
Later <code>silence</code> commands still apply when interruption skips the remaining scene media.


* Use <code>movie_draw_to_yuv()</code> when the movie should own the final display and software RGB conversion or <code>video.txt</code> scaling is undesirable.
The scene command uses the blocking player. Choose the <code>movie_*</code> functions when a controller needs asynchronous playback, screen composition, seeking, repeat, selectable resampling, or independent movie and sound channels.
* Use <code>movie_draw_to_screen()</code> when sprites, text, effects, subscreens, offsets, clipping, black filtering, or deliberate layer order are required.
* Do not alternate hardware YUV presentation between several movie channels as a composition technique. The hardware output is exclusive.
* Width and height affect both paths, but zero dimensions resolve differently: RGB drawing follows the destination screen, while hardware YUV presentation follows the WebM display dimensions.
* Stop the YUV-presented playback normally. OpenBOR restores the configured game video mode automatically.
* Use <code>MOVIE_LOADING_AUTO</code> for a safe general-purpose cache decision.
* Stream long or one-time movies when complete caching would waste RAM.
* Cache short, frequently reused, or seek-heavy clips when storage latency matters and sufficient memory is available.
* Remember that cached sources still require full VP8 and Vorbis decoding for every playback.
* Draw into a creator-owned subscreen when sprites, text, effects, or other screen drawing must share a deliberate layer order with the movie.
* Clear or prepare each destination before drawing the movie. OpenBOR never clears a creator-owned screen automatically.
* Draw active movies regularly while they are visible. Playback continues even when no draw call is made.
* Treat zero width and height as per-destination fill behavior. Use <code>MOVIE_SIZE_NATIVE</code> for native dimensions or explicit values for picture-in-picture layouts.
* Use signed offsets with oversized dimensions for controlled zoom and clipping.
* Enable the black filter only when exact black must survive a subscreen transparency mask.
* Route simultaneous movies to distinct sound channels immediately after each <code>movie_play()</code> call.
* Use seeks for rewind or other backward navigation; negative playback speed is not supported.
* Stop every playback using a source before calling <code>movie_unload()</code>.
* Treat movie pointers as stable channel slots rather than permanent unique playback instances.
* Use the 64-channel mask as a fast state summary, not as a target workload.
* Prefer the modern movie API for new projects. Reserve <code>playwebm()</code> and the scene <code>video</code> command for compatibility or intentionally blocking presentation.


== Related pages ==
== See also ==


* [[Graphics Overview]]
* [[Drawmethod]]
* [[Subscreens]]
* [[Direct Drawing]]
* [[Audio Overview]]
* [[Audio Overview]]
* [[Drawmethod]]
* [[Scenes]]
* [[Drawscreen()|drawscreen]]
* [[WebM]]
* [[Allocscreen()|allocscreen]]
 
[[Category:Openbor]]
[[Category:Openbor]]
[[Category:Script]]
[[Category:Script]]
[[Category:Graphics]]
[[Category:Graphics]]

Latest revision as of 19:33, 28 November 2026

Introduction

OpenBOR plays WebM movies containing VP8 video and optional Vorbis audio. Movies can supply cinematics, animated interfaces, video surfaces, picture-in-picture layouts, or the main content of a module.

The movie system separates playback from drawing. Video and audio decoding run asynchronously on the CPU. The GPU samples the decoded video planes, converts their YUV colors to RGB, and renders the result. Scripts decide when and where to draw the retained frame while the movie channel manages position, pause, speed, repeat, and audio.

Both movie_draw_to_screen() and movie_draw_to_yuv() use GPU rendering. Their difference is the destination: an OpenBOR screen for composition, or the display for direct presentation.

Choosing a drawing destination

Feature Screen composition Direct display
Function movie_draw_to_screen(screen, channel) movie_draw_to_yuv(channel)
Destination Main virtual screen or a creator-owned subscreen. Display window.
Rendering GPU video sampling, YUV-to-RGB conversion, scaling, and drawing. GPU video sampling, YUV-to-RGB conversion, scaling, and presentation.
Placement Movie dimensions and signed destination offsets, clipped to the screen. Centered presentation using logical display dimensions and the display's stretch setting.
Composition Combine movies with sprites, text, effects, and other screen content. Present one movie frame directly. Each call replaces the displayed window content.
Image controls Movie resampling and exact-black protection. Apply drawmethod effects when drawing the resulting screen. Movie resampling and display brightness/gamma correction.
Typical use Video surfaces, captions, interfaces, multiple views, and layered scenes. Full-window movie playback controlled directly by a script or scene.

Drawing uses the channel's retained frame. It does not advance playback or request a separate decode. One retained frame may be drawn repeatedly, sent to several screens, or shown through either drawing function. The renderer reuses its uploaded video planes until playback supplies another frame.

Formats

Component Format
Container WebM. Supply the complete module path, including its extension.
Video VP8. Use even frame dimensions of at least 2 by 2 pixels. The video track must use a non-stereoscopic mode.
Embedded audio Optional Vorbis, mono or stereo. The engine's music sample-rate range is 11,025 through 48,000 Hz.
Screen destination 32-bit OpenBOR screen, including screens created with allocscreen().

The decoder selects the first video track and first audio track. Unsupported video or audio codecs reject playback when the decoder opens. If initialization of a supported optional Vorbis track fails, video may continue silently with the reason recorded in the engine log.

Loading checks that source data can be opened or cached. Codec and track validation takes place when playback opens asynchronously, so a loaded source can still report a playback-opening error.

Sources, playback, and channels

Three identifiers serve different purposes:

Item Returned by Purpose
Source ID movie_load() Identifies a reusable streamed file or cached compressed file.
Playback object movie_play() Provides property access and playback control for a movie channel.
Movie channel index movie_get_channel_index() Selects the movie used by either drawing function.

Movie channels are numbered 0 through 63. MOVIE_CHANNEL_COUNT provides the channel count, and MOVIE_CHANNEL_AUTO requests automatic selection. Automatic selection takes the lowest inactive channel and reports an error when every channel is active. Selecting an explicit index replaces playback on that channel.

The playback pointer identifies an engine-owned channel object. Its address remains stable while the movie system is running, including when the channel is inactive. Reusing the channel replaces its playback state. Coordinate channel ownership between scripts, and use MOVIE_PROPERTY_ACTIVE to check whether a channel is playing. Release playback with movie_stop(); the engine manages the channel object's storage.

Source storage is separate from the 64-channel playback bank and grows as sources are loaded. Source IDs increase during the session and are not reassigned after unloading. Loading the same path twice creates two source IDs. One source may be played on several channels, with independent timing, presentation settings, and audio routing.

Loading modes

Constant Source storage Use
MOVIE_LOADING_STREAM Retains the file path. Each playback opens its own file position and decoder. Playback that reads its compressed data from the module as needed. This is the default.
MOVIE_LOADING_CACHE Reads the complete compressed file into a shared source buffer. Reusing a clip or avoiding repeated reads of its compressed data.
MOVIE_LOADING_AUTO Chooses cached or streamed storage using the engine's source-cache policy. Automatic storage selection.

Cached storage contains the compressed WebM file. Each playback still owns its decoder, frame queues, position, and controls.

Automatic selection uses an aggregate movie-cache budget of one quarter of total system memory and preserves a reserve of at least one eighth of total memory or 128 MiB, whichever is greater. If a cache allocation cannot be satisfied, automatic mode can use streaming. Explicit cache mode reports a failed load. Open or size-validation failures fail loading. During caching, read errors fail the load instead of selecting streaming.

Script playback

movie_load()

movie_load(path [, loading])

Returns an integer source ID. path is the exact module path; OpenBOR does not append an extension. Omitting loading selects MOVIE_LOADING_STREAM.

int source_id = movie_load(
    "data/scenes/intro.webm",
    openborconstant("MOVIE_LOADING_AUTO")
);

Source ID 0 is valid. Invalid paths, empty files, invalid loading modes, and failed source allocations report script errors.

movie_play()

movie_play(source_id [, movie_channel])

Returns the playback object for the acquired movie channel. Omit the second argument, pass NULL(), or use MOVIE_CHANNEL_AUTO for automatic selection.

void playback = movie_play(source_id);
int channel = movie_get_channel_index(playback);

// Select a particular movie channel.
void another_playback = movie_play(source_id, 5);

Every start restores the channel's default properties. Configure the returned playback object after calling movie_play().

Startup is asynchronous. The channel becomes active before its first frame is necessarily ready. Drawing an active channel during startup can therefore complete without displaying a frame. Decoder-opening errors stop that playback and are reported in the engine log.

movie_stop()

movie_stop(playback);

Stops the selected playback and makes its channel available for reuse. The channel's active state, source association, position, and duration are reset. Calling it with a valid inactive channel object leaves that channel inactive.

Decoder teardown can continue asynchronously after the channel becomes inactive. Playback objects remain owned by the engine. Creator-owned destination screens have their own lifetime and can be released with free() when the creator has finished using them.

movie_unload()

movie_unload(source_id);

Releases a loaded source after every playback and retiring decoder has finished using it. Invalid or still-referenced sources report a script error. This function returns no status value for polling.

Source unloading requires completed decoder teardown. Decoder teardown may still retain that source after a channel becomes inactive. The script API has no source-readiness query; checking MOVIE_PROPERTY_ACTIVE alone is insufficient for an immediate unload. Keep reusable sources loaded across playbacks. Movie-system shutdown completes decoder teardown and releases remaining sources automatically.

Basic screen-composition example

The following functions use global variables to retain the controller's state across callbacks. Call initialization once, call drawing while the interface is visible, and call cleanup when closing it. The source remains loaded for reuse.

void movie_example_init()
{
    int source_id = movie_load(
        "data/scenes/intro.webm",
        openborconstant("MOVIE_LOADING_AUTO")
    );
    void playback = movie_play(source_id);
    void screen = allocscreen(320, 180);

    setglobalvar("movie_example_source", source_id);
    setglobalvar("movie_example_playback", playback);
    setglobalvar("movie_example_screen", screen);
}

void movie_example_draw()
{
    void playback = getglobalvar("movie_example_playback");
    void screen = getglobalvar("movie_example_screen");

    if(playback == NULL() || screen == NULL()) return;
    if(!movie_get_property(
        playback, openborconstant("MOVIE_PROPERTY_ACTIVE")
    )) return;

    int channel = movie_get_channel_index(playback);
    clearscreen(screen);
    movie_draw_to_screen(screen, channel);
    drawstringtoscreen(screen, 6, 6, 0, "PLAYING");
    drawscreen(screen, 16, 16, 5000);
}

void movie_example_close()
{
    void playback = getglobalvar("movie_example_playback");
    void screen = getglobalvar("movie_example_screen");

    if(playback != NULL()) movie_stop(playback);
    if(screen != NULL()) free(screen);

    setglobalvar("movie_example_playback", NULL());
    setglobalvar("movie_example_screen", NULL());
}

The drawing function uses the common drawmethod when submitting its completed screen through drawscreen(). Keep that shared state appropriate for the intended presentation, as described in Drawmethod. Close the controller after pending draws that reference its screen have finished.

Screen composition

movie_draw_to_screen()

movie_draw_to_screen(screen, movie_channel)

The first argument is a screen pointer. The second is an integer movie-channel index. Obtain that index with movie_get_channel_index(playback), read MOVIE_PROPERTY_CHANNEL, or supply the channel explicitly selected at playback start.

The function draws the retained frame immediately into the selected screen. Its opaque movie rectangle is clipped to the destination, and pixels outside that rectangle retain their existing contents. Scripts control clearing, layering, later screen submission, and screen lifetime.

Use this sequence when a movie shares a composition with other graphics:

  1. Clear or prepare the destination.
  2. Draw background content.
  3. Draw the movie with movie_draw_to_screen().
  4. Draw captions, sprites, or other overlays.
  5. Submit the completed screen with drawscreen().

Multiple movies drawn into one screen follow call order. Later movie rectangles replace earlier content where they overlap. Movie channel numbers do not determine that order.

movie_draw_to_screen() uses the movie's own size, offset, resampling, and black-filter properties. Global drawmethod state does not control this operation. To rotate, curve, blend, or otherwise transform the complete movie image, draw it into a subscreen and apply Drawmethod settings when drawing that screen.

Main screen and subscreens

Use allocscreen(width, height) to create a subscreen. For a drawing hook that operates directly on the main virtual screen:

void destination = openborvariant("vscreen");
movie_draw_to_screen(destination, channel);

Direct main-screen drawing participates at the point where the script executes. Subsequent drawing can cover it, and a subsequent clear removes it. Playback retains no destination pointer, so each call can select a different screen.

Both drawing functions require an active channel. Before the first frame is ready, a valid draw can do nothing successfully. Invalid channels, inactive channels, invalid screen destinations, and failed rendering report script errors. The drawing functions return no script value.

Dimensions and offsets

Width and height resolve independently:

Property value Screen composition Direct display
0 Use the corresponding destination-screen dimension. Use the corresponding WebM display dimension.
MOVIE_SIZE_NATIVE Use the corresponding decoded-frame dimension. Use the corresponding WebM display dimension.
Positive explicit value Set the movie rectangle's dimension in destination pixels. Set the requested logical display dimension.

Set MOVIE_PROPERTY_OFFSET_X and MOVIE_PROPERTY_OFFSET_Y to place the movie rectangle within a screen. Offsets are signed. Oversized dimensions combined with negative offsets provide zoom-and-crop layouts; smaller dimensions provide inset placement. Set both dimensions appropriately when preserving the movie's aspect ratio.

For a 640 by 360 movie rectangle centered within a 320 by 180 subscreen:

movie_set_property(playback, openborconstant("MOVIE_PROPERTY_WIDTH"), 640);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_HEIGHT"), 360);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_OFFSET_X"), -160);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_OFFSET_Y"), -90);

movie_draw_to_screen(movie_screen, channel);

With width and height both zero, the same playback can fill destinations of different sizes:

movie_set_property(playback, openborconstant("MOVIE_PROPERTY_WIDTH"), 0);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_HEIGHT"), 0);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_OFFSET_X"), 0);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_OFFSET_Y"), 0);

movie_draw_to_screen(large_screen, channel);
movie_draw_to_screen(small_screen, channel);

Both calls draw the same retained frame. Changing dimensions or offsets changes its presentation without restarting playback.

Exact-black protection

Screen transparency settings can use RGB 0, 0, 0 as a transparent key when a subscreen is drawn later. Enable black protection when the movie's black areas should remain visible through such a composition:

movie_set_property(
    playback, openborconstant("MOVIE_PROPERTY_BLACK_FILTER"), 1
);

The GPU first resamples the video planes and converts the result to RGB. It then changes exact output black to RGB 1, 1, 1 when protection is enabled. Other output colors retain their values. This protection is disabled by default and applies to screen composition.

Movie resampling

MOVIE_PROPERTY_RESAMPLE selects the filter used when rendering the decoded video. It applies to screen composition and direct display.

Constant Sampling
DC_RESAMPLE_MOVIE Movie default; equivalent to bilinear.
DC_RESAMPLE_NEAREST Nearest-sample reconstruction.
DC_RESAMPLE_BILINEAR Linear reconstruction between neighboring samples.
DC_RESAMPLE_BICUBIC_CATMULL_ROM Catmull-Rom cubic reconstruction.
DC_RESAMPLE_BICUBIC_MITCHELL Mitchell cubic reconstruction.
DC_RESAMPLE_BICUBIC_BSPLINE B-spline cubic reconstruction.
DC_RESAMPLE_LANCZOS_2 Two-lobe Lanczos reconstruction.
DC_RESAMPLE_LANCZOS_3 Three-lobe Lanczos reconstruction.
movie_set_property(
    playback,
    openborconstant("MOVIE_PROPERTY_RESAMPLE"),
    openborconstant("DC_RESAMPLE_BICUBIC_MITCHELL")
);

int filter = movie_get_property(
    playback, openborconstant("MOVIE_PROPERTY_RESAMPLE")
);

The GPU reconstructs the Y, U, and V planes at their respective resolutions before converting to RGB. Changing this property takes effect when the frame is drawn again, including while playback is paused. It does not seek or restart decoding.

Movie resampling controls video-to-destination rendering. Drawmethod resampling can separately control a subsequent transformed drawscreen() operation. Final display filtering is another stage applied when presenting the completed game screen. See Drawmethod resampling.

Direct display presentation

movie_draw_to_yuv()

movie_draw_to_yuv(channel);

This function renders the retained movie frame directly to the display window and presents it immediately. It clears the window background, centers the movie using the selected logical display dimensions, and applies display brightness and gamma. The display's stretch setting can fill the window.

Logical display dimensions are scaled for the actual window. They are independent of the game screen resolution configured in video.txt; explicit movie width and height are not literal window-pixel extents. Movie X/Y offsets and exact-black protection are screen-composition controls and do not apply here.

Each direct-display call presents a complete movie view. Use screen composition to assemble captions, sprites, several movies, or other overlays into one frame. Direct presentation preserves the normal graphics resources, so ordinary screen rendering and presentation remain available. Stopping a directly presented movie clears its direct-presentation state.

For example, after acquiring an active playback:

movie_set_property(
    playback, openborconstant("MOVIE_PROPERTY_WIDTH"),
    openborconstant("MOVIE_SIZE_NATIVE")
);
movie_set_property(
    playback, openborconstant("MOVIE_PROPERTY_HEIGHT"),
    openborconstant("MOVIE_SIZE_NATIVE")
);

// Call when the controller wants to present the retained movie frame.
if(movie_get_property(playback, openborconstant("MOVIE_PROPERTY_ACTIVE")))
{
    movie_draw_to_yuv(movie_get_channel_index(playback));
}

Position, pause, speed, repeat, interruption, and sound routing use the same playback properties for either destination.

Playback timing and control

Position and duration use milliseconds. The playback clock begins when asynchronous decoder startup is ready. Drawing does not move the clock, and omitting drawing does not pause the movie.

While the movie owns an embedded audio stream, consumed audio provides the playback clock. Video follows that clock, with late frames discarded when necessary to preserve synchronization. Video-only playback uses the movie's own clock. If another audio producer replaces the movie's sound stream, the movie continues from a matching position on its own clock.

Position and seeking

Read MOVIE_PROPERTY_POSITION for the playback position. Write it to request a seek:

movie_set_property(
    playback, openborconstant("MOVIE_PROPERTY_POSITION"), 12500
);

This requests 12.5 seconds. Seeking reopens decoding asynchronously while retaining the displayed frame until replacement frames are ready. When duration is known, a seek at or beyond its end is clamped to the last available millisecond. MOVIE_PROPERTY_DURATION is read-only and remains zero until duration is known.

Use position changes for rewind controls and other backward navigation. Continuous negative-speed playback is not supported.

Pause

Set MOVIE_PROPERTY_PAUSED to 1 to hold the position and displayed frame and pause the movie's audio. Set it to 0 to resume.

movie_set_property(playback, openborconstant("MOVIE_PROPERTY_PAUSED"), 1);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_PAUSED"), 0);

Speed

MOVIE_PROPERTY_SPEED accepts finite nonnegative values. Normal speed is 1.0. Values below 1 slow playback; values above 1 accelerate it. Positive speed changes also change embedded-audio speed and pitch.

Rates above 16.0 are clamped to 16.0, and accepted rates are rounded to the nearest 0.001. Negative or nonfinite values report an error. Zero holds the position and pauses audio. Returning from zero to a positive rate reopens decoding at the held position.

movie_set_property(playback, openborconstant("MOVIE_PROPERTY_SPEED"), 0.5);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_SPEED"), 2.0);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_SPEED"), 1.0);

These statements select half speed, double speed, and normal speed respectively; use the statement matching the desired control action.

Repeat and interruption

Set MOVIE_PROPERTY_REPEAT to 1 to reopen playback from the beginning when it reaches its terminal frame. Scripts can implement a custom loop region by observing position and requesting a seek to its beginning.

MOVIE_PROPERTY_INTERRUPT defaults to 1. New Escape or normal movie-skip input stops interruptible playback during the engine update. Set it to 0 when a controller should handle stopping itself:

movie_set_property(playback, openborconstant("MOVIE_PROPERTY_REPEAT"), 1);
movie_set_property(playback, openborconstant("MOVIE_PROPERTY_INTERRUPT"), 0);

Embedded audio

Movie channels select playback objects. Sound channels select destinations in the audio mixer. Their indexes are separate: movie channels run from 0 through 63, and sound channels run from 0 through 4095.

Each playback initially selects sound channel 0, the music and media channel. Embedded audio replaces the occupant of its selected sound channel. Ordinary movie_play() leaves unrelated sound channels running, and a movie without audio leaves existing sound playback alone.

movie_set_sound_channel()

movie_set_sound_channel(playback, sound_channel)

Routes an active playback's embedded audio to the selected sound channel. Changing the destination reopens decoding asynchronously at the playback position. Selecting the already assigned channel leaves its routing in place. The destination is selected directly, so its existing audio is replaced without priority arbitration.

For simultaneous audible movies, assign separate sound channels immediately after starting each playback:

int source_a = movie_load("data/scenes/feed_a.webm");
int source_b = movie_load("data/scenes/feed_b.webm");

void playback_a = movie_play(source_a, 4);
movie_set_sound_channel(playback_a, 10);

void playback_b = movie_play(source_b, 5);
movie_set_sound_channel(playback_b, 11);

MOVIE_PROPERTY_SOUND_CHANNEL reports this routing and is read-only through the property API. Embedded streams also expose applicable controls through the sound-object API. Seek the movie through MOVIE_PROPERTY_POSITION so audio and video remain coordinated. See Audio Overview.

Movie object API

Use openborconstant() for property and loading-mode names. Channel indexes are ordinary integers.

Channel access

Function Result
movie_get_channel_object(channel) Engine-owned object for that channel, including an inactive channel.
movie_get_channel_index(playback) Index belonging to a valid playback object.
movie_get_channel_mask() Unsigned 64-bit activity mask with one bit per movie channel. Set bits identify active playback on their corresponding channels.

For a particular channel, read its active state directly:

void playback = movie_get_channel_object(5);
int active = movie_get_property(
    playback, openborconstant("MOVIE_PROPERTY_ACTIVE")
);

Property access

movie_get_property(playback, property)
movie_set_property(playback, property, value)

The getter returns the property's value. The setter returns no value. Invalid objects, property identifiers, values, and writes to read-only properties report script errors.

The following defaults describe a newly started playback. Stopping resets the channel; its source becomes invalid and position and duration become zero.

Property Access Default Meaning
MOVIE_PROPERTY_ACTIVE Read 1 after start Whether the channel owns active playback.
MOVIE_PROPERTY_BLACK_FILTER Read/write 0 Protect exact output black during screen composition.
MOVIE_PROPERTY_CHANNEL Read Acquired index Movie channel index.
MOVIE_PROPERTY_DURATION Read 0 until known Unsigned 64-bit duration in milliseconds.
MOVIE_PROPERTY_HEIGHT Read/write 0 Height selection; see Dimensions and offsets.
MOVIE_PROPERTY_INTERRUPT Read/write 1 Allow normal movie-skip input.
MOVIE_PROPERTY_OFFSET_X Read/write 0 Signed horizontal placement within a destination screen.
MOVIE_PROPERTY_OFFSET_Y Read/write 0 Signed vertical placement within a destination screen.
MOVIE_PROPERTY_PAUSED Read/write 0 Hold the playback clock and owned audio stream.
MOVIE_PROPERTY_POSITION Read/write 0 Unsigned 64-bit millisecond position. Writing requests a seek.
MOVIE_PROPERTY_REPEAT Read/write 0 Restart from the beginning at the terminal frame.
MOVIE_PROPERTY_RESAMPLE Read/write DC_RESAMPLE_MOVIE Filter used to render decoded video; the movie default is bilinear.
MOVIE_PROPERTY_SOUND_CHANNEL Read 0 Embedded-audio destination. Change with movie_set_sound_channel().
MOVIE_PROPERTY_SOURCE Read Played source Source ID associated with playback.
MOVIE_PROPERTY_SPEED Read/write 1.0 Forward playback rate, normalized to 0 through 16.
MOVIE_PROPERTY_WIDTH Read/write 0 Width selection; see Dimensions and offsets.

Boolean properties use zero for disabled and nonzero for enabled. Pause, position, speed, and sound-routing changes require active playback. Configure appearance, repeat, and interruption after starting playback because each start restores the defaults.

For a diagnostic listing of the public property map:

movie_get_property(playback, openborconstant("PROPERTY_ACCESS_DUMP"));

This writes the property listing to the engine log.

Blocking playback

Use blocking playback when a movie should complete or be interrupted before its calling script or scene continues.

playwebm()

playwebm(path [, noskip])
int result = playwebm("data/scenes/intro.webm", 0);

noskip defaults to 0, allowing normal skip input. Nonzero disables that input interruption.

Result Meaning
1 Movie completed.
0 Playback failed.
-1 Permitted input interrupted playback.

The function stops existing movie playbacks, opens a streamed source, and presents it directly using the WebM display dimensions. It services input and movie playback while blocking the caller. Width and height use MOVIE_SIZE_NATIVE, playback speed is normal, repeat is disabled, and movie resampling uses its bilinear default.

Movies with embedded audio request exclusive audio playback through sound channel 0. Silent movies allow existing music to continue. Screenshot capture renders the movie through the GPU into a capture screen before reading the completed pixels for the screenshot.

Cleanup completes decoder teardown and releases the temporary source before returning. Normal game rendering remains available after direct movie presentation.

Scene video command

video path [skipone] [noskip]

Both optional flags default to zero.

Setting Behavior
skipone 0 Interrupting a video skips the remaining scene media.
skipone 1 Interrupting a video skips it and continues with subsequent scene commands.
noskip 0 Normal movie-skip input is allowed.
noskip 1 Movie-skip input is disabled.

For example, allow skipping just this video while continuing the scene:

video data/scenes/intro.webm 1 0

Later silence commands still apply when interruption skips the remaining scene media.

The scene command uses the blocking player. Choose the movie_* functions when a controller needs asynchronous playback, screen composition, seeking, repeat, selectable resampling, or independent movie and sound channels.

See also