Home/docs/reference/JSON bridge

JSON bridge

JSON Bridge Reference

Three JSON variant functions and 56 named methods, for hosts that already serialize structured parameters over a platform channel, such as the MethodChannel side of a Dart FFI host. The methods cover Presenter operations, global logging, and frame export. Parameters are passed as a JSON object; call listMethods to query the interfaces the runtime supports.

Entry functions#

char *erika_presenter_invoke_json(ErikaPresenterHandle *handle, const char *method, const char *arguments_json)

Calls a named method. The returned JSON string is owned by the caller; release it with erika_string_free.

char *erika_presenter_render_tick_json(ErikaPresenterHandle *handle, double time_seconds)

JSON variant of render_tick; returns the statistics as JSON.

char *erika_presenter_poll_event_json(ErikaPresenterHandle *handle)

JSON variant of poll_event. Returns NULL when the event queue is empty.

Ownership of returned strings follows the same rules as the C API: release results from invoke_json and render_tick_json with erika_string_free; the NULL that poll_event_json returns when idle needs no release. An unknown method name returns an error response.

Response envelope#

Success response:

{ "ok": true, "status": 0, "value": /* method return value; null when there is none */ }

Failure response:

{ "ok": false, "status": 3, "error": "human readable message" }

Check the ok field. The bridge layer can generate argument or method errors on its own. When a C call fails, it reads the thread-local message and, if that is empty, generates a description from the status. A caught panic becomes an error response; a panic outside the catch scope, or a panic-abort build, may terminate the process. Any non-Ok status from the C layer maps to status: 3.

Event return shape#

The fields of the event object from poll_event_json correspond one-to-one to ErikaEvent. kind is an integer (0–12, 14; see the event table in the C ABI overview):

{ "kind": 1, "status": 0, "state": 2, "durationMicros": 0,
  "positionMicros": 0, "buffering": false,
  "video": { "width": 0, "height": 0, "primaries": 0, "transfer": 0 },
  "tracks": { "video": 0, "audio": 0, "subtitle": 0 } }

Three kinds carry extra fields: Error (9) adds an error string; VideoDecoderChanged (11) adds decoder and message; AudioOutputChanged (12) adds audio and message. Returns NULL when the queue is empty.

Method list#

Parameter names are always camelCase. Optional parameters are in square brackets; when omitted, the C function’s default is used. Only parameters and return values are listed; the semantics match the C function of the same name.

Playback controls

MethodParametersReturnsC function
openuri, [httpHeaders], [httpReadAheadBytes], [httpBackBufferBytes], [startPositionMicros]nullerika_presenter_open_with_options
play—nullerika_presenter_play
pause—nullerika_presenter_pause
stop—nullerika_presenter_stop
close—nullerika_presenter_close
seekpositionMicrosnullerika_presenter_seek
setPlaybackRateratenullerika_presenter_set_playback_rate
setVolumevolumenullerika_presenter_set_volume
setMutedmutednullerika_presenter_set_muted
volume—{volume, muted}JSON bridge
setUpscalermodenullerika_presenter_set_upscaler
loadUpscalerModelFilepath, [name]nullerika_presenter_load_upscaler_model
clearUpscalerModel—nullerika_presenter_clear_upscaler_model
setSubtitleScalescalenullerika_presenter_set_subtitle_scale
setOpenStartPositionpositionMicrosnullerika_presenter_set_open_start_position
setSubtitleDelaydelayMicrosnullerika_presenter_set_subtitle_delay
subtitleDelay—{delayMicros}JSON bridge
subtitleText—{text, cues, mediaOpen}JSON bridge

Tracks

MethodParametersReturnsC function
tracks—Track arrayerika_presenter_tracks
container—{format, bitRate, mediaOpen}JSON bridge
addExternalSubtitleuritrackIderika_presenter_add_external_subtitle
removeSubtitleTracktrackId (signed)nullerika_presenter_remove_subtitle_track
selectAudioTrack[trackId], default -1nullerika_presenter_select_audio_track
selectSubtitleTrack[trackId], default -1nullerika_presenter_select_subtitle_track

In-memory fonts

MethodParametersReturnsC function
selectSubtitleMemoryFontsfontIdsnullerika_presenter_select_subtitle_memory_fonts
clearSubtitleMemoryFonts—nullerika_presenter_clear_subtitle_memory_fonts
getSubtitleMemoryFontStatus—registeredCount, registeredBytes, selectedCount, generation, selectedIdserika_presenter_get_subtitle_memory_font_status

Danmaku

MethodParametersReturnsC function
loadDanmakuFileurinullerika_presenter_load_danmaku_file
loadDanmakuJsonjsonnullerika_presenter_load_danmaku_json
addDanmakuTrackFileuri, [name], [offsetMicros]trackIderika_presenter_add_danmaku_track_file
addDanmakuTrackJsonjson, [name], [offsetMicros]trackIderika_presenter_add_danmaku_track_json
removeDanmakuTracktrackId (unsigned)nullerika_presenter_remove_danmaku_track
setDanmakuTrackEnabledtrackId, [enabled], default truenullerika_presenter_set_danmaku_track_enabled
setDanmakuTrackOffsettrackId, [offsetMicros]nullerika_presenter_set_danmaku_track_offset
setDanmakuGlobalOffset[offsetMicros]nullerika_presenter_set_danmaku_global_offset
danmakuTracks—Danmaku track array (id, enabled, offsetMicros, itemCount, name, source)erika_presenter_danmaku_tracks
clearDanmaku—nullerika_presenter_clear_danmaku
setDanmakuEnabled[enabled], default truenullerika_presenter_set_danmaku_enabled
setDanmakuConfigFields to override (partial)nullerika_presenter_get_danmaku_config + set_danmaku_config (read-modify-write)

Note: the json parameter of loadDanmakuJson and addDanmakuTrackJson follows the unified Danmaku JSON contract. You can pass a standard item array, a root object containing a comments / danmaku / items array, or a JSON Lines string.

setDanmakuConfig is read-modify-write: only the keys you pass are overwritten, and fields you omit keep their current values. Boolean keys: enabled, mergeDuplicates, allowStacking, allowScrollOverwrite, blockTop, blockBottom, blockScroll; numeric keys: fontSize, opacity, displayArea, scrollDurationSeconds, scrollSpeedFactor, trackGapRatio, outlineWidth, shadowOffsetX, shadowOffsetY, maxQuantity, maxLinesPerMode, shadowStyle. There are also two conditional keys: when customFontFamily or customFontFilePath is present, the call goes through erika_presenter_set_danmaku_font; when blockWordsJson is present, it goes through erika_presenter_set_danmaku_block_words_json.

Status queries

MethodParametersReturnsC function
getUpscalerStatus—Upscaler statuserika_presenter_get_upscaler_status
getOutputStatus—Output statuserika_presenter_get_output_status
getPresenterStats—Render statisticserika_presenter_get_stats
getResourceStatus—Resource statuserika_presenter_get_resource_status

setOpenStartPosition sets the start for the next open. Positive setSubtitleDelay values delay subtitles, negative values advance them, clamped to ±10 minutes. subtitleDelay returns the current offset; subtitleText returns delay-adjusted text, cues and mediaOpen. ASS override tags are removed; bitmap subtitles have no text.

setMuted preserves the chosen volume. container returns the demuxer short name, overall bit rate and media-open state. Video tracks include the container-signaled dolbyVisionProfile. loadUpscalerModelFile loads from a file path; select Custom mode afterward. The diagnostics snapshot also exposes engine, reason, and lastGpuMs in upscaler.

Method discovery, chapters, and diagnostics · 0.3.0#

listMethods returns {schema, methods}. Each entry contains name, scope, summary, arguments (name / type / required), returns, blocking, and writesFiles; the table that the current runtime returns is authoritative. Global methods need no handle; Presenter methods need a valid handle. The entries describe synchronous blocking and possible file writes; they do not imply asynchronous task scheduling.

C

char *methods = erika_presenter_invoke_json(NULL, "listMethods", "{}");
// Parse, then free
erika_string_free(methods);
MethodParameters / returnsScope
listMethodsNo parameters; returns the full method table.global
invokeJsonmethod, [arguments]; returns the full response envelope of the invoked method.presenter
setDebugHudEnabledenabled; returns null.presenter
setOutputHeadroomheadroom, known; returns null.presenter
trackSelectionNo parameters; returns {video, audio, subtitle}; null means nothing is selected.presenter
setSubtitleFont[fontFamily], [fontFilePath]; returns null.presenter
setSubtitleStyleThe camelCase fields of ErikaSubtitleStyle; returns null.presenter
getDanmakuConfigNo parameters; returns the current layout configuration.presenter
chaptersNo parameters; returns {chapters:[{index,title,startMs,endMs}], mediaOpen}.presenter
getDiagnosticsSnapshotNo parameters; returns a schema 1 diagnostics document with the actual decoding path, output, audio, buffering, and timing statistics.presenter
getLogs[limit], [minLevel] (trace/debug/info/warn/error), [sinceSeq]; returns a redacted log document and nextSeq.global
exportFrameuri, positionMillis; optional width, height, format (png / rgba), outputPath, overwrite, httpHeaders, httpReadAheadBytes. Returns dataBase64 when no path is specified.global
exportFramesuri, positionsMillis, outputDir; the other options are the same as for single-frame export. Returns the source size, duration, seek and decode counts, and per-frame results.global

Chapter positions are in milliseconds, and endMs can be null; to pass one to seek, convert startMs to microseconds. Single-frame and batch export are synchronous, blocking operations that may write files, so run them on a worker thread, not the UI thread. Batch export reuses the decoder; if a single frame fails, the failure is recorded on its entry and the rest continue.

Export results include timestampMicros, the source dimensions, and toneMapped; HDR is tone-mapped to SDR. For the detailed memory and threading rules, see Frame export C entry points. A log limit of 0 reads all retained entries, and sinceSeq takes the nextSeq from the previous call. The log ring keeps at most 2000 entries / 512 KiB.

Example#

// Seek to 30 seconds
char *out = erika_presenter_invoke_json(p,
    "seek", "{ \"positionMicros\": 30000000 }");
// {"ok":true,"status":0,"value":null}
erika_string_free(out);

// Open with request headers: httpHeaders is a name-to-value object, not an array
out = erika_presenter_invoke_json(p, "open",
    "{ \"uri\": \"https://example.com/v.mp4\", "
    "\"httpHeaders\": { \"Referer\": \"https://example.com\" } }");
erika_string_free(out);

// Poll for events: returns NULL when the queue is empty
char *ev = erika_presenter_poll_event_json(p);
if (ev) { erika_string_free(ev); }
liberika v0.3.8 Section Reference License MPL-2.0