Skip to content

Subtitles

NihilDigit edited this page Nov 28, 2026 · 1 revision

Subtitles

SubtitleEndpoint.kt provides two subtitle capabilities backed by PikPak's cloud index and real-time speech-to-text service:

  1. Cloud subtitle lookup (GET /oracle/subtitle) — fetches uploaded, extracted, or speech-generated subtitle files indexed by GCID.
  2. Real-time AI subtitles (GET /subsrelay/v1/node + WebSocket) — streams live 16 kHz mono PCM audio to a subsrelay node and receives timestamped caption cues, optional translation, and quota updates.

Cloud subtitle lookup

val subtitles = client.getCloudSubtitles(
    gcid = fileGcid,
    durationSeconds = videoDurationSeconds, // optional; sent as `duration` when > 0
)

Each CloudSubtitle carries gcid, url, ext (without leading dot, e.g. "srt", "ass", "ssa"), name, durationMs, languages, score, and source (CloudSubtitleSource.UPLOADED = 0, EXTRACTED = 1, SPEECH = 2).

Real-time AI subtitles (subsrelay)

1. Discover node and quota

val node = client.getAiSubtitleNode(gcid)
// node.url, node.sourceLanguage, node.supportedLanguages, node.quota
  • When the account's period allowance is exhausted (node.quota?.exceeded == true), getAiSubtitleNode throws AiSubtitleQuotaExceededException (carrying node, with errorDescription set to nextResetTime when non-blank).
  • For non-primary audio tracks of the same file, derive a distinct track GCID with aiSubtitleAudioTrackGcid(fileGcid, streamIndex) (SHA-1("$canonicalGcid/audio/$streamIndex"), uppercase hex) so tracks do not collide in subsrelay's per-GCID caption cache.
  • When client.domain is pikpakdrive.com or pikpak.me, the server may echo subsrelay.pikpakdrive.com or subsrelay.pikpak.me (NXDOMAIN in public DNS). openAiSubtitleSession normalises those suffixes back to .mypikpak.com automatically, mirroring OSS upload endpoint normalisation.

2. Open a session and stream audio

openAiSubtitleSession has two overloads: pass an already resolved node.url, or pass AiSubtitleStart alone to resolve the node and connect in one call.

val (node, session) = client.openAiSubtitleSession(
    AiSubtitleStart(
        gcid = trackGcid,
        mediaId = mediaId,
        fileId = fileId,
        targetLanguage = "zh-CN", // from node.supportedLanguages, or "" for original speech
    ),
)

Audio expectations (AiSubtitleAudioFormat):

  • Encoding: pcm_s16le, 16_000 Hz, 1 channel (mono).
  • Recommended frame size: 100 ms per binary frame (RECOMMENDED_FRAME_MS), fed ~10 s ahead of playback (RECOMMENDED_LEAD_MS) so cues arrive before speech is heard.
  • Wire framing (handled inside AiSubtitleSession): 2-byte big-endian JSON header length, UTF-8 {"position_ms":<positionMs>}, followed by raw PCM bytes.

Sending audio and control signals:

  • trySendAudio(positionMs, pcm) — non-blocking; drops and returns false once the 256-frame outbound queue reaches half capacity so control frames never stall behind audio.
  • sendAudio(positionMs, pcm) — suspending counterpart.
  • trySendControl(control) / sendControl(control) — sends AiSubtitleControl.SEEK, PAUSE, RESUME, FINALIZE, or STOP.

3. Consume events and close cleanly

for (event in session.events) {
    when (event) {
        is AiSubtitleEvent.Cue -> renderCue(event.cue) // startMs, endMs, text, language
        is AiSubtitleEvent.Quota -> updateQuota(event.quota)
        is AiSubtitleEvent.Error -> if (!event.isRecoverable) handleError(event)
        is AiSubtitleEvent.Stop -> if (event.isQuotaExceeded) showQuotaExceeded()
    }
}
  • AiSubtitleEvent.Error.isRecoverable is true for soniox_unavailable, where the server leaves the socket open for subsequent audio frames.
  • One concurrent session per account: subsrelay allows only one active WebSocket session per account. Always finish with session.closeGracefully(timeout = 3.seconds) (sends {"type":"stop"} behind queued frames and waits for the server to close the socket and release the slot) before opening a replacement session. Non-suspending session.close() is also available as AutoCloseable for synchronous teardown.

WebSocket client lifecycle

WebSocket upgrades require HTTP/1.1 and live for the duration of a video without an overall request timeout. PikPakClient creates a dedicated WebSocket HttpClient lazily on first use (OkHttp pinned to HTTP/1.1 on JVM/Android, Darwin on Apple) and closes it in PikPakClient.close(). If you inject your own httpClient, the SDK reuses it when WebSockets is already installed, or derives a lightweight config { install(WebSockets) } copy that it owns and closes.

Clone this wiki locally