Skip to content

SubtitlesIndicator

roosit edited this page Oct 16, 2026 · 1 revision

SubtitlesIndicator

Up | Previous | Next | Русский

Full source with short explanations

Below is the full source of the class in documentation form. The comments inside the block explain the purpose of the parts of the class, but they are not stored in the working file SubtitlesIndicator.java: the production code stays clean and the explanations live in the wiki.

package com.velitask.plugin.official;

import com.velitask.sdk.FrameContext;
import com.velitask.sdk.Indicator;
import com.velitask.sdk.IndicatorContext;
import com.velitask.sdk.data.SubtitleSensorAtom;
import com.velitask.sdk.properties.ColorProperty;
import com.velitask.sdk.properties.EnumArrayProperty;
import com.velitask.sdk.properties.FontColorProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.SubtitleSensorProperty;
import com.velitask.sdk.properties.TextAlignProperty;
import com.velitask.sdk.properties.TransparentColorProperty;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import org.abricos.core.state.maket.HorizontalAlign;
import org.abricos.core.state.maket.Maket;
import org.abricos.core.state.maket.VerticalAlign;

public class SubtitlesIndicator extends Indicator {

    /* Indicator name; the full layer name in JSON: com.velitask.plagin.official.subtitles. */
    public static final String NAME = "subtitles";

    /* Prefix of the indicator's localization keys. */
    private static final String KEY = _KEY + "." + NAME;

    /* Subtitle sensor (an SRT/VTT/ASS track from the source). */
    private final SubtitleSensorProperty mSensor = new SubtitleSensorProperty();

    /* Display mode: block, by words, by characters, karaoke. */
    private final DisplayModeProperty mMode = new DisplayModeProperty();

    /* Font and color of the main text; the default size is 48. */
    private final FontColorProperty mFont
            = new FontColorProperty("font", localized(KEY + ".font.title"), 48);

    /* Highlight color for the "Karaoke" mode: F5C242. */
    private final ColorProperty mHighlight
            = new ColorProperty(new Color(0xF5, 0xC2, 0x42), "highlight", localized(KEY + ".highlight.title"));

    /* Backdrop: color (black) and transparency 0..100 (45 by default). */
    private final TransparentColorProperty mBackground
            = new TransparentColorProperty("bg", localized(KEY + ".bg.title"), Color.BLACK, 45);

    /* Text alignment in the layer: bottom center by default. */
    private final TextAlignProperty mTextAlign = new TextAlignProperty(TextAlignProperty.TextAlign.BOTTOM_CENTER);

    /* Detail level: "Compact" reduces line breaks to spaces. */
    private final DetailLevelProperty mDetail = new DetailLevelProperty();

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public String getTitle() {
        return localized(KEY + ".title");
    }

    @Override
    public String getDescription() {
        return localized(KEY + ".description");
    }

    @Override
    public String getTags() {
        return localized(KEY + ".tags");
    }

    @Override
    /* Default maket: bottom center, layer 1400 x 200. */
    public void defineMaket(Maket maket) {
        maket.setVertical(VerticalAlign.BOTTOM);
        maket.setHorizontal(HorizontalAlign.CENTER);
        maket.setLayerMargin(null, null, 80d, null);
        maket.setLayerSize(1400d, 200d);
    }

    @Override
    /* The order of properties defines the order in the panel and in JSON. */
    public IProperty[] defineProperties() {
        return new IProperty[]{
            mSensor,
            mMode,
            mFont,
            mHighlight,
            mBackground,
            mTextAlign,
            mDetail
        };
    }

    @Override
    /* Draws one frame. */
    public void render(IndicatorContext indicatorContext) {
        SubtitlesContext ctx = (SubtitlesContext) indicatorContext;
        Graphics2D g = ctx.graphics;

        /* No data or empty text: draw nothing. */
        SubtitleSensorAtom atom = ctx.sensor.queryAtom();
        if (atom == null || atom.text == null || atom.text.isEmpty()) {
            return;
        }

        DisplayMode mode = ctx.mode.value;
        DetailLevel detail = ctx.detail.value;

        /* In compact mode, line breaks are replaced with spaces. */
        String base = atom.text;
        if (detail == DetailLevel.COMPACT) {
            base = base.replace('\n', ' ').trim();
        }

        /* How many characters (code points) of the current cue should already be shown. */
        int revealCp = revealCodePoints(atom);

        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        Font font = ctx.font.toFont(ctx.scale);
        g.setFont(font);

        Color baseColor = ctx.font.color.value;
        Color highlightColor = ctx.highlight.value;

        /* The text visible in this frame depends on the display mode. */
        String shown = switch (mode) {
            case BLOCK ->
                base;
            case REVEAL_CHARS ->
                cutByCodePoints(base, revealCp);
            case REVEAL_WORDS ->
                revealByWords(base, revealCp);
            case KARAOKE ->
                base;
        };
        if (shown.isEmpty()) {
            return;
        }

        /* The text is drawn line by line. */
        String[] lines = shown.split("\n", -1);

        /* The backdrop first, then the text. */
        drawBackground(g, ctx, lines, font);

        if (mode == DisplayMode.KARAOKE) {
            drawKaraoke(g, ctx, lines, revealCp, baseColor, highlightColor, font);
        } else {
            drawBlock(g, ctx, lines, baseColor, font);
        }
    }

    /* The part of the cue elapsed by the current time, in characters. */
    private int revealCodePoints(SubtitleSensorAtom atom) {
        long span = atom.cueEndRaw - atom.cueStartRaw;
        double p = span <= 0 ? 1.0 : (double) (atom.timeRaw - atom.cueStartRaw) / span;
        p = Math.max(0.0, Math.min(1.0, p));
        return (int) Math.round(atom.charLength * p);
    }

    /* Cuts a string by the number of characters (taking surrogate pairs into account). */
    private static String cutByCodePoints(String s, int cpCount) {
        if (cpCount <= 0) {
            return "";
        }
        int total = s.codePointCount(0, s.length());
        if (cpCount >= total) {
            return s;
        }
        return s.substring(0, s.offsetByCodePoints(0, cpCount));
    }

    /* Reveal by words: an unfinished word is not shown. */
    private static String revealByWords(String s, int cpCount) {
        String cut = cutByCodePoints(s, cpCount);
        if (cut.length() == s.length() || cut.isEmpty()) {
            return cut;
        }
        char next = s.charAt(cut.length());
        if (Character.isWhitespace(next)) {
            return cut;
        }
        int lastWs = -1;
        for (int i = cut.length() - 1; i >= 0; i--) {
            if (Character.isWhitespace(cut.charAt(i))) {
                lastWs = i;
                break;
            }
        }
        return lastWs < 0 ? "" : cut.substring(0, lastWs);
    }

    /* A rounded backdrop sized to the text block. */
    private void drawBackground(Graphics2D g, SubtitlesContext ctx, String[] lines, Font font) {
        if (ctx.background.alpha <= 0f) {
            return;
        }
        FontMetrics fm = g.getFontMetrics(font);
        int lineH = fm.getHeight();
        int blockH = lineH * lines.length;
        int maxW = 0;
        for (String line : lines) {
            maxW = Math.max(maxW, fm.stringWidth(line));
        }
        int pad = Math.round(fm.getAscent() * 0.4f);
        int boxW = Math.min(ctx.width, maxW + pad * 2);
        int boxH = Math.min(ctx.height, blockH + pad * 2);
        int x = anchorX(ctx.textAlign.value, ctx.width, boxW);
        int y = anchorY(ctx.textAlign.value, ctx.height, boxH);

        Color base = ctx.background.color;
        Color fill = new Color(base.getRed(), base.getGreen(), base.getBlue(),
                Math.round(ctx.background.alpha * 255));
        g.setColor(fill);
        g.fillRoundRect(x, y, boxW, boxH, pad, pad);
    }

    /* Plain output of lines with the chosen alignment. */
    private void drawBlock(Graphics2D g, SubtitlesContext ctx, String[] lines, Color color, Font font) {
        FontMetrics fm = g.getFontMetrics(font);
        int lineH = fm.getHeight();
        int blockH = lineH * lines.length;
        int topY = anchorY(ctx.textAlign.value, ctx.height, blockH);
        g.setColor(color);
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            int lineW = fm.stringWidth(line);
            int x = anchorX(ctx.textAlign.value, ctx.width, lineW);
            int y = topY + i * lineH + fm.getAscent();
            g.drawString(line, x, y);
        }
    }

    /* Output that paints the already "sung" part in the highlight color. */
    private void drawKaraoke(Graphics2D g, SubtitlesContext ctx, String[] lines,
            int revealCp, Color baseColor, Color highlightColor, Font font) {
        FontMetrics fm = g.getFontMetrics(font);
        int lineH = fm.getHeight();
        int blockH = lineH * lines.length;
        int topY = anchorY(ctx.textAlign.value, ctx.height, blockH);

        int consumedCp = 0;
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            int lineW = fm.stringWidth(line);
            int x = anchorX(ctx.textAlign.value, ctx.width, lineW);
            int y = topY + i * lineH + fm.getAscent();

            int lineCp = line.isEmpty() ? 0 : line.codePointCount(0, line.length());
            int revealInLine = Math.max(0, Math.min(lineCp, revealCp - consumedCp));

            if (revealInLine <= 0) {
                g.setColor(baseColor);
                g.drawString(line, x, y);
            } else if (revealInLine >= lineCp) {
                g.setColor(highlightColor);
                g.drawString(line, x, y);
            } else {
                int splitIdx = line.offsetByCodePoints(0, revealInLine);
                String revealed = line.substring(0, splitIdx);
                String rest = line.substring(splitIdx);
                g.setColor(highlightColor);
                g.drawString(revealed, x, y);
                g.setColor(baseColor);
                g.drawString(rest, x + fm.stringWidth(revealed), y);
            }

            consumedCp += lineCp + 1;
        }
    }

    /* Horizontal anchoring by alignment. */
    private static int anchorX(TextAlignProperty.TextAlign align, int width, int contentW) {
        return switch (align) {
            case TOP_LEFT, CENTER_LEFT, BOTTOM_LEFT ->
                0;
            case TOP_CENTER, CENTER, BOTTOM_CENTER ->
                (width - contentW) / 2;
            case TOP_RIGHT, CENTER_RIGHT, BOTTOM_RIGHT ->
                width - contentW;
        };
    }

    /* Vertical anchoring by alignment. */
    private static int anchorY(TextAlignProperty.TextAlign align, int height, int contentH) {
        return switch (align) {
            case TOP_LEFT, TOP_CENTER, TOP_RIGHT ->
                0;
            case CENTER_LEFT, CENTER, CENTER_RIGHT ->
                (height - contentH) / 2;
            case BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT ->
                height - contentH;
        };
    }

    /* Display modes (the order defines the index in JSON). */
    public enum DisplayMode {
        BLOCK,
        REVEAL_WORDS,
        REVEAL_CHARS,
        KARAOKE
    }

    /* Detail levels (the order defines the index in JSON). */
    public enum DetailLevel {
        COMPACT,
        STANDARD,
        FULL
    }

    /* The enum property "Display mode" (default "Whole block"). */
    public static class DisplayModeProperty extends EnumArrayProperty<DisplayMode> {

        private static final String KEY_MODE = KEY + ".mode";

        public DisplayModeProperty() {
            super(DisplayMode.class);
        }

        @Override
        public String getName() {
            return "mode";
        }

        @Override
        public String getTitle() {
            return localized(KEY_MODE + ".title");
        }

        @Override
        protected String[] defineTitles() {
            DisplayMode[] vs = DisplayMode.values();
            String[] t = new String[vs.length];
            for (int i = 0; i < vs.length; i++) {
                t[i] = switch (vs[i]) {
                    case BLOCK ->
                        localized(KEY_MODE + ".block");
                    case REVEAL_WORDS ->
                        localized(KEY_MODE + ".revealWords");
                    case REVEAL_CHARS ->
                        localized(KEY_MODE + ".revealChars");
                    case KARAOKE ->
                        localized(KEY_MODE + ".karaoke");
                };
            }
            return t;
        }
    }

    /* The enum property "Detail level" (default "Standard"). */
    public static class DetailLevelProperty extends EnumArrayProperty<DetailLevel> {

        private static final String KEY_DETAIL = KEY + ".detail";

        public DetailLevelProperty() {
            super(DetailLevel.class);
            set(DetailLevel.STANDARD);
        }

        @Override
        public String getName() {
            return "detail";
        }

        @Override
        public String getTitle() {
            return localized(KEY_DETAIL + ".title");
        }

        @Override
        protected String[] defineTitles() {
            DetailLevel[] vs = DetailLevel.values();
            String[] t = new String[vs.length];
            for (int i = 0; i < vs.length; i++) {
                t[i] = switch (vs[i]) {
                    case COMPACT ->
                        localized(KEY_DETAIL + ".compact");
                    case STANDARD ->
                        localized(KEY_DETAIL + ".standard");
                    case FULL ->
                        localized(KEY_DETAIL + ".full");
                };
            }
            return t;
        }
    }

    /* A snapshot of property values for one frame. */
    public class SubtitlesContext extends IndicatorContext {

        public final SubtitleSensorProperty.SensorContext sensor;
        public final DisplayModeProperty.ArrayContext mode;
        public final FontColorProperty.FontColorContext font;
        public final ColorProperty.ColorContext highlight;
        public final TransparentColorProperty.TransparentColorContext background;
        public final TextAlignProperty.TextAlignContext textAlign;
        public final DetailLevelProperty.ArrayContext detail;

        public SubtitlesContext(FrameContext frame) {
            super(frame);
            sensor = mSensor.createContext(frame);
            mode = mMode.createContext(frame);
            font = mFont.createContext(frame);
            highlight = mHighlight.createContext(frame);
            background = mBackground.createContext(frame);
            textAlign = mTextAlign.createContext(frame);
            detail = mDetail.createContext(frame);
        }
    }

    @Override
    /* Creates the frame context. */
    public IndicatorContext createContext(FrameContext frame) {
        return new SubtitlesContext(frame);
    }
}

Purpose

SubtitlesIndicator draws the current subtitle cue (SRT, VTT, ASS) over the video. A cue can appear whole, by words, by characters, or in "karaoke" mode with the already spoken part highlighted. There can be a semi-transparent backdrop under the text.

How it works

Data. SubtitleSensorProperty (the SensorType.SUBTITLE sensor, the sensors_subtitle_data table) is used to request a SubtitleSensorAtom for the current moment. The fields used are text (the cue text), charLength (length in characters), cueStartRaw and cueEndRaw (the cue boundaries) and timeRaw (the current time). The elapsed fraction of the cue p = (timeRaw - cueStartRaw) / (cueEndRaw - cueStartRaw) is clamped to the range 0..1 (for a zero or negative cue length, p = 1); the number of shown characters is revealCp = round(charLength × p). If there is no atom or text is empty, the indicator draws nothing.

Settings. Seven properties in the order of defineProperties():

  • Subtitle is a SubtitleSensorProperty;
  • mode is a DisplayModeProperty (EnumArrayProperty<DisplayMode>: BLOCK, REVEAL_WORDS, REVEAL_CHARS, KARAOKE; default BLOCK);
  • font is a FontColorProperty with size 48;
  • highlight is a ColorProperty, highlight color F5C242;
  • bg is a TransparentColorProperty: black color, transparency 45 (on a 0..100 scale);
  • textAlign is a TextAlignProperty, BOTTOM_CENTER by default;
  • detail is a DetailLevelProperty (EnumArrayProperty<DetailLevel>: COMPACT, STANDARD, FULL; default STANDARD).

No display groups are set through configureDisplay, and there are no skins.

Drawing. The order is: choose the text by mode → split into lines → backdrop (drawBackground, only if the backdrop alpha is greater than zero) → text. BLOCK and KARAOKE take the full text; REVEAL_CHARS cuts it to revealCp characters (cutByCodePoints); REVEAL_WORDS does the same but does not show an unfinished word (revealByWords). In KARAOKE (drawKaraoke) each line is drawn in two colors: the already "passed" part in the highlight color and the rest in the main font color; the character counter continues across a line break (each break counts as one character). In the other modes (drawBlock) the lines are output in the main color. The line coordinates are computed by anchorX and anchorY according to the chosen alignment.

The backdrop is a rounded rectangle sized to the text block plus the padding pad = 0.4 × ascent, but no larger than the layer; color and transparency: alpha = (100 − transparency) / 100.

Features and limitations

  • The detail property affects only COMPACT. In this mode, line breaks in the cue are replaced with spaces and the ends are trimmed. The code makes no difference between STANDARD and FULL.
  • The backdrop is computed from the already "revealed" text. In the by-words and by-characters modes, the backdrop size grows together with the text.
  • With no cue at the moment, the indicator draws nothing, and there is no backdrop either.
  • The font size is not fitted: a long cue that does not fit into the layer is cut off by the layer boundaries.
  • Karaoke counts by characters, not by words, so the highlight moves smoothly across the whole line.
  • In the REVEAL_WORDS mode, at the start of a cue (the first word not finished yet) an empty string is output: the indicator draws nothing until the end of the first word.

Clone this wiki locally