Coverage Report

Created: 2026-11-30 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mpv/sub/sd_ass.c
Line
Count
Source
1
/*
2
 * This file is part of mpv.
3
 *
4
 * mpv is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Lesser General Public
6
 * License as published by the Free Software Foundation; either
7
 * version 2.1 of the License, or (at your option) any later version.
8
 *
9
 * mpv is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
16
 */
17
18
#include <stdlib.h>
19
#include <assert.h>
20
#include <string.h>
21
#include <math.h>
22
#include <limits.h>
23
24
#include <libavutil/common.h>
25
#include <ass/ass.h>
26
27
#include "mpv_talloc.h"
28
29
#include "config.h"
30
#include "options/m_config.h"
31
#include "options/options.h"
32
#include "options/path.h"
33
#include "common/common.h"
34
#include "common/msg.h"
35
#include "demux/demux.h"
36
#include "demux/packet_pool.h"
37
#include "video/csputils.h"
38
#include "video/mp_image.h"
39
#include "dec_sub.h"
40
#include "ass_mp.h"
41
#include "packer.h"
42
#include "sd.h"
43
44
struct sd_ass_priv {
45
    struct ass_library *ass_library;
46
    struct ass_renderer *ass_renderer;
47
    struct ass_track *ass_track;
48
    struct ass_track *shadow_track; // for --sub-ass=no rendering
49
    bool ass_configured;
50
    bool is_converted;
51
    struct lavc_conv *converter;
52
    struct sd_filter **filters;
53
    int num_filters;
54
    bool clear_once;
55
    struct mp_sub_packer *packer;
56
    struct sub_bitmap_copy_cache *copy_cache;
57
    bstr last_text;
58
    struct mp_image_params video_params;
59
    struct mp_image_params last_params;
60
    struct mp_osd_res osd;
61
    struct seen_packet *seen_packets;
62
    int num_seen_packets;
63
    bool check_animated;
64
};
65
66
struct seen_packet {
67
    int64_t sig;
68
    double pts;
69
    int animated; // -1 is unknown
70
};
71
72
#undef OPT_BASE_STRUCT
73
#define OPT_BASE_STRUCT struct mp_sub_filter_opts
74
75
const struct m_sub_options mp_sub_filter_opts = {
76
    .opts = (const struct m_option[]){
77
        {"sdh", OPT_BOOL(sub_filter_SDH)},
78
        {"sdh-harder", OPT_BOOL(sub_filter_SDH_harder)},
79
        {"sdh-enclosures", OPT_STRINGLIST(sub_filter_SDH_enclosures)},
80
        {"regex-enable", OPT_BOOL(rf_enable)},
81
        {"regex-plain", OPT_BOOL(rf_plain)},
82
        {"regex", OPT_STRINGLIST(rf_items)},
83
        {"jsre", OPT_STRINGLIST(jsre_items)},
84
        {"regex-warn", OPT_BOOL(rf_warn)},
85
        {0}
86
    },
87
    .size = sizeof(OPT_BASE_STRUCT),
88
    .defaults = &(OPT_BASE_STRUCT){
89
        .sub_filter_SDH_enclosures = (char *[]) {
90
            "()",
91
            "[]",
92
            "\uFF08\uFF09",
93
            NULL
94
        },
95
        .rf_enable = true,
96
    },
97
    .change_flags = UPDATE_SUB_FILT,
98
};
99
100
static void mangle_colors(struct sd *sd, struct sub_bitmaps *parts);
101
static void fill_plaintext(struct sd *sd, double pts);
102
103
static const struct sd_filter_functions *const filters[] = {
104
    // Note: list order defines filter order.
105
    &sd_filter_sdh,
106
#if HAVE_POSIX
107
    &sd_filter_regex,
108
#endif
109
#if HAVE_JAVASCRIPT
110
    &sd_filter_jsre,
111
#endif
112
    NULL,
113
};
114
115
// Add default styles, if the track does not have any styles yet.
116
// Apply style overrides if the user provides any.
117
static void mp_ass_add_default_styles(struct sd *sd, ASS_Track *track, struct mp_subtitle_opts *opts,
118
                                      struct mp_subtitle_shared_opts *shared_opts)
119
0
{
120
0
    if (opts->ass_styles_file && shared_opts->ass_style_override[sd->order]) {
121
0
        char *file = mp_get_user_path(NULL, sd->global, opts->ass_styles_file);
122
0
        ass_read_styles(track, file, NULL);
123
0
        talloc_free(file);
124
0
    }
125
126
0
    if (track->n_styles == 0) {
127
0
        if (!track->PlayResY) {
128
0
            track->PlayResX = MP_ASS_FONT_PLAYRESX;
129
0
            track->PlayResY = MP_ASS_FONT_PLAYRESY;
130
0
        }
131
0
        track->Kerning = true;
132
0
        int sid = ass_alloc_style(track);
133
0
        track->default_style = sid;
134
0
        ASS_Style *style = track->styles + sid;
135
0
        style->Name = strdup("Default");
136
0
        mp_ass_set_style(style, track->PlayResY, opts->sub_style);
137
0
    }
138
139
0
    if (shared_opts->ass_style_override[sd->order])
140
0
        ass_process_force_style(track);
141
0
}
142
143
static const char *const font_mimetypes[] = {
144
    "application/x-truetype-font",
145
    "application/vnd.ms-opentype",
146
    "application/x-font-otf",
147
    "application/x-font-ttf",
148
    "application/x-font", // probably incorrect
149
    "application/font-sfnt",
150
    "font/collection",
151
    "font/otf",
152
    "font/sfnt",
153
    "font/ttf",
154
    NULL
155
};
156
157
static const char *const font_exts[] = {".ttf", ".ttc", ".otf", ".otc", NULL};
158
159
static bool attachment_is_font(struct mp_log *log, struct demux_attachment *f)
160
0
{
161
0
    if (!f->name || !f->type || !f->data || !f->data_size)
162
0
        return false;
163
0
    for (int n = 0; font_mimetypes[n]; n++) {
164
0
        if (strcmp(font_mimetypes[n], f->type) == 0)
165
0
            return true;
166
0
    }
167
    // fallback: match against file extension
168
0
    char *ext = strlen(f->name) > 4 ? f->name + strlen(f->name) - 4 : "";
169
0
    for (int n = 0; font_exts[n]; n++) {
170
0
        if (strcasecmp(ext, font_exts[n]) == 0) {
171
0
            mp_warn(log, "Loading font attachment '%s' with MIME type %s. "
172
0
                    "Assuming this is a broken Matroska file, which was "
173
0
                    "muxed without setting a correct font MIME type.\n",
174
0
                    f->name, f->type);
175
0
            return true;
176
0
        }
177
0
    }
178
0
    return false;
179
0
}
180
181
static void add_subtitle_fonts(struct sd *sd)
182
0
{
183
0
    struct sd_ass_priv *ctx = sd->priv;
184
0
    struct mp_subtitle_opts *opts = sd->opts;
185
0
    if (!opts->ass_enabled || !opts->use_embedded_fonts || !sd->attachments)
186
0
        return;
187
0
    for (int i = 0; i < sd->attachments->num_entries; i++) {
188
0
        struct demux_attachment *f = &sd->attachments->entries[i];
189
0
        if (attachment_is_font(sd->log, f))
190
0
            ass_add_font(ctx->ass_library, f->name, f->data, f->data_size);
191
0
    }
192
0
}
193
194
static void filters_destroy(struct sd *sd)
195
0
{
196
0
    struct sd_ass_priv *ctx = sd->priv;
197
198
0
    for (int n = 0; n < ctx->num_filters; n++) {
199
0
        struct sd_filter *ft = ctx->filters[n];
200
0
        if (ft->driver->uninit)
201
0
            ft->driver->uninit(ft);
202
0
        talloc_free(ft);
203
0
    }
204
0
    ctx->num_filters = 0;
205
0
}
206
207
static void filters_init(struct sd *sd)
208
0
{
209
0
    struct sd_ass_priv *ctx = sd->priv;
210
211
0
    filters_destroy(sd);
212
213
0
    for (int n = 0; filters[n]; n++) {
214
0
        struct sd_filter *ft = talloc_ptrtype(ctx, ft);
215
0
        *ft = (struct sd_filter){
216
0
            .global = sd->global,
217
0
            .log = sd->log,
218
0
            .packet_pool = demux_packet_pool_get(sd->global),
219
0
            .opts = mp_get_config_group(ft, sd->global, &mp_sub_filter_opts),
220
0
            .driver = filters[n],
221
0
            .codec = "ass",
222
0
            .event_format = talloc_strdup(ft, ctx->ass_track->event_format),
223
0
        };
224
0
        if (ft->driver->init(ft)) {
225
0
            MP_TARRAY_APPEND(ctx, ctx->filters, ctx->num_filters, ft);
226
0
        } else {
227
0
            talloc_free(ft);
228
0
        }
229
0
    }
230
0
}
231
232
static void enable_output(struct sd *sd, bool enable)
233
0
{
234
0
    struct sd_ass_priv *ctx = sd->priv;
235
0
    if (enable == !!ctx->ass_renderer)
236
0
        return;
237
0
    if (ctx->ass_renderer) {
238
0
        ass_renderer_done(ctx->ass_renderer);
239
0
        ctx->ass_renderer = NULL;
240
0
    } else {
241
0
        ctx->ass_renderer = ass_renderer_init(ctx->ass_library);
242
243
0
        mp_ass_configure_fonts(ctx->ass_renderer, sd->opts->sub_style,
244
0
                               sd->global, sd->log);
245
0
    }
246
0
}
247
248
static void assobjects_init(struct sd *sd)
249
0
{
250
0
    struct sd_ass_priv *ctx = sd->priv;
251
0
    struct mp_subtitle_opts *opts = sd->opts;
252
0
    struct mp_subtitle_shared_opts *shared_opts = sd->shared_opts;
253
254
0
    ctx->ass_library = mp_ass_init(sd->global, sd->opts->sub_style, sd->log);
255
0
    ass_set_extract_fonts(ctx->ass_library, opts->use_embedded_fonts);
256
257
0
    add_subtitle_fonts(sd);
258
259
0
    if (shared_opts->ass_style_override[sd->order])
260
0
        ass_set_style_overrides(ctx->ass_library, opts->ass_style_override_list);
261
262
0
    ctx->ass_track = ass_new_track(ctx->ass_library);
263
0
    ctx->ass_track->track_type = TRACK_TYPE_ASS;
264
265
0
    ctx->shadow_track = ass_new_track(ctx->ass_library);
266
0
    ctx->shadow_track->PlayResX = MP_ASS_FONT_PLAYRESX;
267
0
    ctx->shadow_track->PlayResY = MP_ASS_FONT_PLAYRESY;
268
0
    mp_ass_add_default_styles(sd, ctx->shadow_track, opts, shared_opts);
269
270
0
    char *extradata = sd->codec->extradata;
271
0
    int extradata_size = sd->codec->extradata_size;
272
0
    if (ctx->converter) {
273
0
        extradata = lavc_conv_get_extradata(ctx->converter);
274
0
        extradata_size = extradata ? strlen(extradata) : 0;
275
0
    }
276
0
    if (extradata)
277
0
        ass_process_codec_private(ctx->ass_track, extradata, extradata_size);
278
279
0
    mp_ass_add_default_styles(sd, ctx->ass_track, opts, shared_opts);
280
281
0
#if LIBASS_VERSION >= 0x01302000
282
0
    ass_set_check_readorder(ctx->ass_track, sd->opts->sub_clear_on_seek ? 0 : 1);
283
0
#endif
284
285
0
#if LIBASS_VERSION >= 0x01703010
286
0
    ass_configure_prune(ctx->ass_track, sd->opts->ass_prune_delay * 1000.0);
287
0
#endif
288
289
0
    enable_output(sd, true);
290
0
    ass_set_cache_limits(ctx->ass_renderer, sd->opts->sub_glyph_limit, sd->opts->sub_bitmap_max_size);
291
0
}
292
293
static void assobjects_destroy(struct sd *sd)
294
0
{
295
0
    struct sd_ass_priv *ctx = sd->priv;
296
297
0
    ass_free_track(ctx->ass_track);
298
0
    ass_free_track(ctx->shadow_track);
299
0
    enable_output(sd, false);
300
0
    ass_library_done(ctx->ass_library);
301
0
}
302
303
static int init(struct sd *sd)
304
0
{
305
0
    struct sd_ass_priv *ctx = talloc_zero(sd, struct sd_ass_priv);
306
0
    sd->priv = ctx;
307
308
    // Note: accept "null" as alias for "ass", so EDL delay_open subtitle
309
    //       streams work.
310
0
    if (strcmp(sd->codec->codec, "ass") != 0 &&
311
0
        strcmp(sd->codec->codec, "null") != 0)
312
0
    {
313
0
        ctx->is_converted = true;
314
0
        ctx->converter = lavc_conv_create(sd);
315
0
        if (!ctx->converter)
316
0
            return -1;
317
0
    }
318
319
0
    assobjects_init(sd);
320
0
    filters_init(sd);
321
322
0
    ctx->packer = mp_sub_packer_alloc(ctx);
323
324
    // Subtitles does not have any profile value, so put the converted type as a profile.
325
0
    const char *_Atomic *desc = ctx->converter ? &sd->codec->codec_profile : &sd->codec->codec_desc;
326
0
    switch (ctx->ass_track->track_type) {
327
0
    case TRACK_TYPE_ASS:
328
0
        *desc = "Advanced Sub Station Alpha";
329
0
        break;
330
0
    case TRACK_TYPE_SSA:
331
0
        *desc = "Sub Station Alpha";
332
0
        break;
333
0
    }
334
335
0
    return 0;
336
0
}
337
338
// Check if subtitle has events that would cause it to be animated inside {}
339
static bool is_animated(const char *str)
340
0
{
341
0
    const char *begin = str;
342
0
    while ((str = strchr(str, '{'))) {
343
0
        if (str++ > begin && str[-2] == '\\')
344
0
            continue;
345
346
0
        const char *end = strchr(str, '}');
347
0
        if (!end)
348
0
            return false;
349
350
0
        while ((str = memchr(str, '\\', end - str))) {
351
0
            while (str[0] == '\\')
352
0
                ++str;
353
0
            while (str[0] == ' ' || str[0] == '\t')
354
0
                ++str;
355
0
            if (str[0] == 'k' || str[0] == 'K' || str[0] == 't' ||
356
0
                (str[0] == 'f' && str[1] == 'a' && str[2] == 'd') ||
357
0
                (str[0] == 'm' && str[1] == 'o' && str[2] == 'v' && str[3] == 'e'))
358
0
            {
359
0
                return true;
360
0
            }
361
0
        }
362
363
0
        str = end + 1;
364
0
    }
365
366
0
    return false;
367
0
}
368
369
// Note: pkt is not necessarily a fully valid refcounted packet.
370
static void filter_and_add(struct sd *sd, struct demux_packet *pkt)
371
0
{
372
0
    struct sd_ass_priv *ctx = sd->priv;
373
0
    struct demux_packet *orig_pkt = pkt;
374
0
    ASS_Track *track = ctx->ass_track;
375
0
    int old_n_events = track->n_events;
376
377
0
    for (int n = 0; n < ctx->num_filters; n++) {
378
0
        struct sd_filter *ft = ctx->filters[n];
379
0
        struct demux_packet *npkt = ft->driver->filter(ft, pkt);
380
0
        if (pkt != npkt && pkt != orig_pkt)
381
0
            talloc_free(pkt);
382
0
        pkt = npkt;
383
0
        if (!pkt)
384
0
            return;
385
0
    }
386
387
0
    ass_process_chunk(ctx->ass_track, pkt->buffer, pkt->len,
388
0
                      floor(pkt->pts * 1000 + 1e-6),
389
0
                      floor(pkt->duration * 1000 + 1e-6));
390
0
    if (pkt != orig_pkt)
391
0
        talloc_free(pkt);
392
    // the seen and animated state is kept on the original packet
393
0
    pkt = orig_pkt;
394
395
    // This bookkeeping only has any practical use for ASS subs
396
    // over a VO with no video.
397
0
    if (!ctx->is_converted) {
398
0
        if (!pkt->seen) {
399
0
            for (int n = track->n_events - 1; n >= 0; n--) {
400
0
                if (n + 1 == old_n_events || pkt->animated == 1)
401
0
                    break;
402
0
                ASS_Event *event = &track->events[n];
403
                // Might as well mark pkt->animated here with effects if we can.
404
0
                pkt->animated = (event->Effect && event->Effect[0]) ? 1 : -1;
405
0
                if (ctx->check_animated && pkt->animated != 1)
406
0
                    pkt->animated = is_animated(event->Text);
407
0
            }
408
0
            ctx->seen_packets[pkt->seen_pos].animated = pkt->animated;
409
0
        } else {
410
0
            if (ctx->check_animated && ctx->seen_packets[pkt->seen_pos].animated == -1) {
411
0
                for (int n = track->n_events - 1; n >= 0; n--) {
412
0
                    if (n + 1 == old_n_events || pkt->animated == 1)
413
0
                        break;
414
0
                    ASS_Event *event = &track->events[n];
415
0
                    ctx->seen_packets[pkt->seen_pos].animated = is_animated(event->Text);
416
0
                    pkt->animated = ctx->seen_packets[pkt->seen_pos].animated;
417
0
                }
418
0
            } else {
419
0
                pkt->animated = ctx->seen_packets[pkt->seen_pos].animated;
420
0
            }
421
0
        }
422
0
    }
423
0
}
424
425
// 64-bit FNV-1a
426
static inline uint64_t hash_data(const unsigned char *data, size_t len)
427
0
{
428
0
    uint64_t hash = 0xcbf29ce484222325; // offset basis
429
0
    for (size_t n = 0; n < len; n++)
430
0
        hash = (hash ^ data[n]) * 0x100000001b3; // FNV prime
431
0
    return hash;
432
0
}
433
434
// Test if the packet with the given file position and pts was already consumed.
435
// Return false if the packet is new (and add it to the internal list), and
436
// return true if it was already seen. Packets without a file position are
437
// identified by a hash of their contents instead.
438
static bool check_packet_seen(struct sd *sd, struct demux_packet *packet)
439
0
{
440
0
    struct sd_ass_priv *priv = sd->priv;
441
0
    int64_t sig = packet->pos >= 0 ? packet->pos
442
0
                                   : hash_data(packet->buffer, packet->len);
443
0
    int a = 0;
444
0
    int b = priv->num_seen_packets;
445
0
    while (a < b) {
446
0
        int mid = a + (b - a) / 2;
447
0
        struct seen_packet *seen_packet = &priv->seen_packets[mid];
448
0
        if (sig == seen_packet->sig && packet->pts == seen_packet->pts) {
449
0
            packet->seen_pos = mid;
450
0
            return true;
451
0
        }
452
0
        if (sig > seen_packet->sig ||
453
0
            (sig == seen_packet->sig && packet->pts > seen_packet->pts)) {
454
0
            a = mid + 1;
455
0
        } else {
456
0
            b = mid;
457
0
        }
458
0
    }
459
0
    packet->seen_pos = a;
460
0
    MP_TARRAY_INSERT_AT(priv, priv->seen_packets, priv->num_seen_packets, a,
461
0
                        (struct seen_packet){sig, packet->pts, -1});
462
0
    return false;
463
0
}
464
465
0
#define UNKNOWN_DURATION (INT_MAX / 1000)
466
467
static void decode(struct sd *sd, struct demux_packet *packet)
468
0
{
469
0
    struct sd_ass_priv *ctx = sd->priv;
470
0
    ASS_Track *track = ctx->ass_track;
471
472
0
    packet->sub_duration = packet->duration;
473
474
0
    if (ctx->converter) {
475
0
        if (!sd->opts->sub_clear_on_seek && check_packet_seen(sd, packet))
476
0
            return;
477
478
0
        double sub_pts = 0;
479
0
        double sub_duration = 0;
480
0
        char **r = lavc_conv_decode(ctx->converter, packet, &sub_pts,
481
0
                                    &sub_duration);
482
0
        if (sd->opts->sub_stretch_durations ||
483
0
            packet->duration < 0 || sub_duration == UINT32_MAX) {
484
0
            MP_VERBOSE(sd, "Subtitle with unknown duration.\n");
485
0
            sub_duration = UNKNOWN_DURATION;
486
0
        }
487
488
0
        for (int n = 0; r && r[n]; n++) {
489
0
            struct demux_packet pkt2 = {
490
0
                .pts = sub_pts,
491
0
                .duration = sub_duration,
492
0
                .buffer = r[n],
493
0
                .len = strlen(r[n]),
494
0
            };
495
0
            filter_and_add(sd, &pkt2);
496
0
        }
497
0
        for (int n = track->n_events - 1; n >= 0; n--) {
498
0
            if (track->events[track->n_events - 1].Start == track->events[n].Start)
499
0
                continue;
500
0
            if (track->events[n].Duration == UNKNOWN_DURATION * 1000) {
501
0
                if (track->events[n].Start < track->events[n + 1].Start) {
502
0
                    track->events[n].Duration = track->events[n + 1].Start -
503
0
                                                track->events[n].Start;
504
0
                } else if (track->events[n].Start == track->events[n + 1].Start) {
505
0
                    track->events[n].Duration = track->events[n + 1].Duration;
506
0
                }
507
0
            }
508
0
            if (n > 0 && track->events[n].Start != track->events[n - 1].Start)
509
0
                break;
510
0
        }
511
0
    } else {
512
        // Note that for this packet format, libass has an internal mechanism
513
        // for discarding duplicate (already seen) packets but we check this
514
        // anyways for our purposes for ASS subtitles.
515
0
        packet->seen = check_packet_seen(sd, packet);
516
0
        filter_and_add(sd, packet);
517
0
    }
518
0
}
519
520
// Calculate the height used for scaling subtitle text size so --sub-scale-with-window
521
// can undo this scale and use frame size instead. The algorithm used is the following:
522
// - If use_margins is disabled, the text is scaled with the visual size of the video.
523
// - If use_margins is enabled, the text is scaled with the size of the video
524
//   as if the video is resized to "fit" the size of the frame.
525
static float get_libass_scale_height(struct mp_osd_res *dim, bool use_margins)
526
0
{
527
0
    float vidw = dim->w - (dim->ml + dim->mr);
528
0
    float vidh = dim->h - (dim->mt + dim->mb);
529
0
    if (!use_margins || vidw < 1.0)
530
0
        return vidh;
531
0
    else
532
0
        return MPMIN(dim->h, dim->w / vidw * vidh);
533
0
}
534
535
static void configure_ass(struct sd *sd, struct mp_osd_res *dim,
536
                          bool converted, ASS_Track *track)
537
0
{
538
0
    struct mp_subtitle_opts *opts = sd->opts;
539
0
    struct mp_subtitle_shared_opts *shared_opts = sd->shared_opts;
540
0
    struct sd_ass_priv *ctx = sd->priv;
541
0
    ASS_Renderer *priv = ctx->ass_renderer;
542
543
0
    ass_set_frame_size(priv, dim->w, dim->h);
544
0
    ass_set_margins(priv, dim->mt, dim->mb, dim->ml, dim->mr);
545
546
0
    bool set_use_margins = false;
547
0
    float set_sub_pos = 0.0f;
548
0
    float set_line_spacing = 0;
549
0
    float set_font_scale = 1;
550
0
    int set_hinting = 0;
551
0
    bool set_scale_with_window = false;
552
0
    bool set_scale_by_window = true;
553
0
    bool total_override = false;
554
555
    // With forced overrides, apply the --sub-* specific options
556
0
    if (converted || shared_opts->ass_style_override[sd->order] == ASS_STYLE_OVERRIDE_FORCE) {
557
0
        set_scale_with_window = opts->sub_scale_with_window;
558
0
        set_use_margins = opts->sub_use_margins;
559
0
        set_scale_by_window = opts->sub_scale_by_window;
560
0
        total_override = true;
561
0
    } else {
562
0
        set_scale_with_window = opts->ass_scale_with_window;
563
0
        set_use_margins = opts->ass_use_margins;
564
0
    }
565
0
    if (converted || shared_opts->ass_style_override[sd->order]) {
566
0
        set_sub_pos = 100.0f - shared_opts->sub_pos[sd->order];
567
0
        set_line_spacing = opts->sub_line_spacing;
568
0
        set_hinting = opts->sub_hinting;
569
0
    }
570
0
    if (total_override || shared_opts->ass_style_override[sd->order] == ASS_STYLE_OVERRIDE_SCALE) {
571
0
        set_font_scale = shared_opts->sub_scale[sd->order];
572
0
    }
573
0
    if (set_scale_with_window) {
574
0
        set_font_scale *= dim->h / MPMAX(get_libass_scale_height(dim, set_use_margins), 1);
575
0
    }
576
0
    if (!set_scale_by_window) {
577
0
        double factor = dim->h / 720.0;
578
0
        if (factor != 0.0)
579
0
            set_font_scale /= factor;
580
0
    }
581
0
    ass_set_use_margins(priv, set_use_margins);
582
0
    ass_set_line_position(priv, set_sub_pos);
583
0
    ass_set_shaper(priv, opts->sub_shaper);
584
0
    int set_force_flags = 0;
585
0
    if (total_override) {
586
0
        set_force_flags |= ASS_OVERRIDE_BIT_FONT_NAME
587
0
                            | ASS_OVERRIDE_BIT_FONT_SIZE_FIELDS
588
0
                            | ASS_OVERRIDE_BIT_COLORS
589
0
                            | ASS_OVERRIDE_BIT_BORDER;
590
0
        if (!opts->sub_scale_signs)
591
0
            set_force_flags |= ASS_OVERRIDE_BIT_SELECTIVE_FONT_SCALE;
592
0
#if LIBASS_VERSION >= 0x01703020
593
0
        set_force_flags |= ASS_OVERRIDE_BIT_BLUR;
594
0
#endif
595
0
    }
596
0
    if (shared_opts->ass_style_override[sd->order] == ASS_STYLE_OVERRIDE_SCALE &&
597
0
        !opts->sub_scale_signs)
598
0
        set_force_flags |= ASS_OVERRIDE_BIT_SELECTIVE_FONT_SCALE;
599
0
    if (converted)
600
0
        set_force_flags |= ASS_OVERRIDE_BIT_ALIGNMENT;
601
0
#if LIBASS_VERSION >= 0x01306000
602
0
    if ((converted || shared_opts->ass_style_override[sd->order]) && opts->ass_justify)
603
0
        set_force_flags |= ASS_OVERRIDE_BIT_JUSTIFY;
604
0
#endif
605
0
    ass_set_selective_style_override_enabled(priv, set_force_flags);
606
0
    ASS_Style style = {0};
607
0
    mp_ass_set_style(&style, MP_ASS_FONT_PLAYRESY, opts->sub_style);
608
0
    ass_set_selective_style_override(priv, &style);
609
0
    free(style.FontName);
610
0
    if (converted && track->default_style < track->n_styles) {
611
0
        mp_ass_set_style(track->styles + track->default_style,
612
0
                         track->PlayResY, opts->sub_style);
613
0
    }
614
0
    ass_set_font_scale(priv, set_font_scale);
615
0
    ass_set_hinting(priv, set_hinting);
616
0
    ass_set_line_spacing(priv, set_line_spacing);
617
0
#if LIBASS_VERSION >= 0x01600010
618
0
    if (converted) {
619
0
        ass_track_set_feature(track, ASS_FEATURE_WRAP_UNICODE, 1);
620
0
        if (!opts->sub_vsfilter_bidi_compat) {
621
0
            for (int n = 0; n < track->n_styles; n++) {
622
0
                track->styles[n].Encoding = -1;
623
0
            }
624
0
            ass_track_set_feature(track, ASS_FEATURE_BIDI_BRACKETS, 1);
625
0
            ass_track_set_feature(track, ASS_FEATURE_WHOLE_TEXT_LAYOUT, 1);
626
0
        }
627
0
    }
628
0
#endif
629
0
    if (converted) {
630
0
        bool override_playres = true;
631
0
        char **ass_style_override_list = opts->ass_style_override_list;
632
0
        for (int i = 0; ass_style_override_list && ass_style_override_list[i]; i++) {
633
0
            if (bstr_find0(bstr0(ass_style_override_list[i]), "PlayResX") >= 0)
634
0
                override_playres = false;
635
0
        }
636
637
        // srt to ass conversion from ffmpeg has fixed PlayResX of 384 with an
638
        // aspect of 4:3. Starting with libass f08f8ea5 (pre 0.17) PlayResX
639
        // affects shadow and border widths, among others, so to render borders
640
        // and shadows correctly, we adjust PlayResX according to the DAR.
641
        // But PlayResX also affects margins, so we adjust those too.
642
        // This should ensure basic srt-to-ass ffmpeg conversion has correct
643
        // borders, but there could be other issues with some srt extensions
644
        // and/or different source formats which would be exposed over time.
645
        // Make these adjustments only if the user didn't set PlayResX.
646
0
        if (override_playres) {
647
0
            int vidw = dim->w - (dim->ml + dim->mr);
648
0
            int vidh = dim->h - (dim->mt + dim->mb);
649
0
            track->PlayResX = track->PlayResY * (double)vidw / MPMAX(vidh, 1);
650
            // ffmpeg and mpv use a default PlayResX of 384 when it is not known,
651
            // this comes from VSFilter.
652
0
            double fix_margins = track->PlayResX / (double)MP_ASS_FONT_PLAYRESX;
653
0
            for (int n = 0; n < track->n_styles; n++) {
654
0
                track->styles[n].MarginL = lrint(track->styles[n].MarginL * fix_margins);
655
0
                track->styles[n].MarginR = lrint(track->styles[n].MarginR * fix_margins);
656
0
                track->styles[n].MarginV = lrint(track->styles[n].MarginV * set_font_scale);
657
0
            }
658
0
        }
659
0
    }
660
0
}
661
662
static bool has_overrides(char *s)
663
0
{
664
0
    if (!s)
665
0
        return false;
666
0
    return strstr(s, "\\pos") || strstr(s, "\\move") || strstr(s, "\\clip") ||
667
0
           strstr(s, "\\iclip") || strstr(s, "\\org") || strstr(s, "\\p");
668
0
}
669
670
0
#define END(ev) ((ev)->Start + (ev)->Duration)
671
672
static long long find_timestamp(struct sd *sd, double pts)
673
0
{
674
0
    struct sd_ass_priv *priv = sd->priv;
675
0
    if (pts == MP_NOPTS_VALUE)
676
0
        return 0;
677
678
0
    long long ts = floor(pts * 1000 + 1e-6);
679
680
0
    if (!sd->opts->sub_fix_timing ||
681
0
        sd->shared_opts->ass_style_override[sd->order] == ASS_STYLE_OVERRIDE_NONE)
682
0
        return ts;
683
684
    // Try to fix small gaps and overlaps.
685
0
    ASS_Track *track = priv->ass_track;
686
0
    int threshold = sd->opts->sub_fix_timing_threshold;
687
0
    int keep = sd->opts->sub_fix_timing_keep;
688
689
    // Find the "current" event.
690
0
    ASS_Event *ev[2] = {0};
691
0
    int n_ev = 0;
692
0
    for (int n = 0; n < track->n_events; n++) {
693
0
        ASS_Event *event = &track->events[n];
694
0
        if (ts >= event->Start - threshold && ts <= END(event) + threshold) {
695
0
            if (n_ev >= MP_ARRAY_SIZE(ev))
696
0
                return ts; // multiple overlaps - give up (probably complex subs)
697
0
            ev[n_ev++] = event;
698
0
        }
699
0
    }
700
701
0
    if (n_ev != 2)
702
0
        return ts;
703
704
    // Simple/minor heuristic against destroying typesetting.
705
0
    if (ev[0]->Style != ev[1]->Style || has_overrides(ev[0]->Text) ||
706
0
        has_overrides(ev[1]->Text))
707
0
        return ts;
708
709
    // Sort by start timestamps.
710
0
    if (ev[0]->Start > ev[1]->Start)
711
0
        MPSWAP(ASS_Event*, ev[0], ev[1]);
712
713
    // We want to fix partial overlaps only.
714
0
    if (END(ev[0]) >= END(ev[1]))
715
0
        return ts;
716
717
0
    if (ev[0]->Duration < keep || ev[1]->Duration < keep)
718
0
        return ts;
719
720
    // Gap between the events -> move ts to show the end of the first event.
721
0
    if (ts >= END(ev[0]) && ts < ev[1]->Start && END(ev[0]) < ev[1]->Start &&
722
0
        END(ev[0]) + threshold >= ev[1]->Start)
723
0
        return END(ev[0]) - 1;
724
725
    // Overlap -> move ts to the (exclusive) end of the first event.
726
    // Relies on the fact that the ASS_Renderer has no overlap registered, even
727
    // if there is one. This happens to work because we never render the
728
    // overlapped state, and libass never resolves a collision.
729
0
    if (ts >= ev[1]->Start && ts <= END(ev[0]) && END(ev[0]) > ev[1]->Start &&
730
0
        END(ev[0]) <= ev[1]->Start + threshold)
731
0
        return END(ev[0]);
732
733
0
    return ts;
734
0
}
735
736
#undef END
737
738
static struct sub_bitmaps *get_bitmaps(struct sd *sd, struct mp_osd_res dim,
739
                                       int format, double pts)
740
0
{
741
0
    struct sd_ass_priv *ctx = sd->priv;
742
0
    struct mp_subtitle_opts *opts = sd->opts;
743
0
    struct mp_subtitle_shared_opts *shared_opts = sd->shared_opts;
744
0
    bool no_ass = !opts->ass_enabled ||
745
0
        shared_opts->ass_style_override[sd->order] == ASS_STYLE_OVERRIDE_STRIP;
746
0
    bool converted = (ctx->is_converted && !lavc_conv_is_styled(ctx->converter)) || no_ass;
747
0
    ASS_Track *track = no_ass ? ctx->shadow_track : ctx->ass_track;
748
0
    ASS_Renderer *renderer = ctx->ass_renderer;
749
0
    struct sub_bitmaps *res = &(struct sub_bitmaps){0};
750
751
    // Always update the osd_res
752
0
    struct mp_osd_res old_osd = ctx->osd;
753
0
    ctx->osd = dim;
754
755
0
    if (pts == MP_NOPTS_VALUE || !renderer)
756
0
        goto done;
757
758
    // Currently no supported text sub formats support a distinction between forced
759
    // and unforced lines, so we just assume everything's unforced and discard everything.
760
    // If we ever see a format that makes this distinction, we can add support here.
761
0
    if (opts->sub_forced_events_only)
762
0
        goto done;
763
764
0
    double scale = dim.display_par;
765
0
    if (!converted && (!shared_opts->ass_style_override[sd->order] ||
766
0
                       opts->ass_use_video_data >= 1))
767
0
    {
768
        // Let's factor in video PAR for vsfilter compatibility:
769
0
        double par = opts->ass_video_aspect > 0 ?
770
0
                opts->ass_video_aspect :
771
0
                ctx->video_params.p_w / (double)ctx->video_params.p_h;
772
0
        if (isnormal(par))
773
0
            scale *= par;
774
0
    }
775
0
    if (!ctx->ass_configured || !osd_res_equals(old_osd, ctx->osd)) {
776
0
        configure_ass(sd, &dim, converted, track);
777
0
        ctx->ass_configured = true;
778
0
    }
779
0
    ass_set_pixel_aspect(renderer, scale);
780
0
    if (!converted && (!shared_opts->ass_style_override[sd->order] ||
781
0
                       opts->ass_use_video_data >= 2))
782
0
    {
783
0
        ass_set_storage_size(renderer, ctx->video_params.w, ctx->video_params.h);
784
0
    } else {
785
0
        ass_set_storage_size(renderer, 0, 0);
786
0
    }
787
0
    long long ts = find_timestamp(sd, pts);
788
789
0
    if (no_ass)
790
0
        fill_plaintext(sd, pts);
791
792
0
    int changed;
793
0
    ASS_Image *imgs = ass_render_frame(renderer, track, ts, &changed);
794
0
    mp_sub_packer_pack_ass(ctx->packer, &imgs, 1, changed, !converted, format, res);
795
796
0
done:
797
    // mangle_colors() modifies the color field, so copy the thing _before_.
798
0
    res = sub_bitmaps_copy(&ctx->copy_cache, res);
799
800
0
    if (!converted && res)
801
0
        mangle_colors(sd, res);
802
803
0
    return res;
804
0
}
805
806
#define MAX_BUF_SIZE 1024 * 1024
807
#define MIN_EXPAND_SIZE 4096
808
809
static void append(bstr *b, char c)
810
0
{
811
0
    bstr_xappend(NULL, b, (bstr){&c, 1});
812
0
}
813
814
static void ass_to_plaintext(bstr *b, const char *in)
815
0
{
816
0
    const char *open_tag_pos = NULL;
817
0
    bool in_drawing = false;
818
0
    while (*in) {
819
0
        if (open_tag_pos) {
820
0
            if (in[0] == '}') {
821
0
                in += 1;
822
0
                open_tag_pos = NULL;
823
0
            } else if (in[0] == '\\' && in[1] == 'p' && in[2] != 'o') {
824
0
                in += 2;
825
                // Skip text between \pN and \p0 tags. A \p without a number
826
                // is the same as \p0, and leading 0s are also allowed.
827
0
                in_drawing = false;
828
0
                while (in[0] >= '0' && in[0] <= '9') {
829
0
                    if (in[0] != '0')
830
0
                        in_drawing = true;
831
0
                    in += 1;
832
0
                }
833
0
            } else {
834
0
                in += 1;
835
0
            }
836
0
        } else {
837
0
            if (in[0] == '\\' && (in[1] == 'N' || in[1] == 'n')) {
838
0
                in += 2;
839
0
                append(b, '\n');
840
0
            } else if (in[0] == '\\' && in[1] == 'h') {
841
0
                in += 2;
842
0
                append(b, ' ');
843
0
            } else if (in[0] == '{') {
844
0
                open_tag_pos = in;
845
0
                in += 1;
846
0
            } else {
847
0
                if (!in_drawing)
848
0
                    append(b, in[0]);
849
0
                in += 1;
850
0
            }
851
0
        }
852
0
    }
853
    // A '{' without a closing '}' is always visible.
854
0
    if (open_tag_pos) {
855
0
        bstr_xappend(NULL, b, bstr0(open_tag_pos));
856
0
    }
857
0
}
858
859
// Empty string counts as whitespace.
860
static bool is_whitespace_only(bstr b)
861
0
{
862
0
    for (int n = 0; n < b.len; n++) {
863
0
        if (b.start[n] != ' ' && b.start[n] != '\t')
864
0
            return false;
865
0
    }
866
0
    return true;
867
0
}
868
869
static bstr get_text_buf(struct sd *sd, double pts, enum sd_text_type type)
870
0
{
871
0
    struct sd_ass_priv *ctx = sd->priv;
872
0
    ASS_Track *track = ctx->ass_track;
873
874
0
    if (pts == MP_NOPTS_VALUE)
875
0
        return (bstr){0};
876
0
    long long ipts = find_timestamp(sd, pts);
877
878
0
    bstr *b = &ctx->last_text;
879
880
0
    if (!b->start)
881
0
        b->start = talloc_size(ctx, 4096);
882
883
0
    b->len = 0;
884
885
0
    for (int i = 0; i < track->n_events; ++i) {
886
0
        ASS_Event *event = track->events + i;
887
0
        if (ipts >= event->Start && ipts < event->Start + event->Duration) {
888
0
            if (event->Text) {
889
0
                int start = b->len;
890
0
                if (type == SD_TEXT_TYPE_PLAIN) {
891
0
                    ass_to_plaintext(b, event->Text);
892
0
                } else if (type == SD_TEXT_TYPE_ASS_FULL) {
893
0
                    long long s = event->Start;
894
0
                    long long e = s + event->Duration;
895
896
0
                    ASS_Style *style = (event->Style < 0 || event->Style >= track->n_styles) ? NULL : &track->styles[event->Style];
897
898
0
                    int sh = (s / 60 / 60 / 1000);
899
0
                    int sm = (s / 60 / 1000) % 60;
900
0
                    int ss = (s / 1000) % 60;
901
0
                    int sc = (s / 10) % 100;
902
0
                    int eh = (e / 60 / 60 / 1000);
903
0
                    int em = (e / 60 / 1000) % 60;
904
0
                    int es = (e / 1000) % 60;
905
0
                    int ec = (e / 10) % 100;
906
907
0
                    bstr_xappend_asprintf(NULL, b, "Dialogue: %d,%d:%02d:%02d.%02d,%d:%02d:%02d.%02d,%s,%s,%04d,%04d,%04d,%s,%s",
908
0
                        event->Layer,
909
0
                        sh, sm, ss, sc,
910
0
                        eh, em, es, ec,
911
0
                        (style && style->Name) ? style->Name : "", event->Name,
912
0
                        event->MarginL, event->MarginR, event->MarginV,
913
0
                        event->Effect, event->Text);
914
0
                } else {
915
0
                    bstr_xappend(NULL, b, bstr0(event->Text));
916
0
                }
917
0
                if (is_whitespace_only(bstr_cut(*b, start))) {
918
0
                    b->len = start;
919
0
                } else {
920
0
                    append(b, '\n');
921
0
                }
922
0
            }
923
0
        }
924
0
    }
925
926
0
    bstr_eatend(b, (bstr)bstr0_lit("\n"));
927
928
0
    return *b;
929
0
}
930
931
static char *get_text(struct sd *sd, double pts, enum sd_text_type type)
932
0
{
933
0
    return bstrto0(NULL, get_text_buf(sd, pts, type));
934
0
}
935
936
static struct sd_times get_times(struct sd *sd, double pts)
937
0
{
938
0
    struct sd_ass_priv *ctx = sd->priv;
939
0
    ASS_Track *track = ctx->ass_track;
940
0
    struct sd_times res = { .start = MP_NOPTS_VALUE, .end = MP_NOPTS_VALUE };
941
942
0
    if (pts == MP_NOPTS_VALUE)
943
0
        return res;
944
945
0
    long long ipts = find_timestamp(sd, pts);
946
947
0
    for (int i = 0; i < track->n_events; ++i) {
948
0
        ASS_Event *event = track->events + i;
949
0
        if (ipts >= event->Start && ipts < event->Start + event->Duration) {
950
0
            double start = event->Start / 1000.0;
951
0
            double end = event->Duration == UNKNOWN_DURATION ?
952
0
                MP_NOPTS_VALUE : (event->Start + event->Duration) / 1000.0;
953
954
0
            if (res.start == MP_NOPTS_VALUE || res.start > start)
955
0
                res.start = start;
956
957
0
            if (res.end == MP_NOPTS_VALUE || res.end < end)
958
0
                res.end = end;
959
0
        }
960
0
    }
961
962
0
    return res;
963
0
}
964
965
static void fill_plaintext(struct sd *sd, double pts)
966
0
{
967
0
    struct sd_ass_priv *ctx = sd->priv;
968
0
    ASS_Track *track = ctx->shadow_track;
969
970
0
    ass_flush_events(track);
971
972
0
    bstr text = get_text_buf(sd, pts, SD_TEXT_TYPE_PLAIN);
973
0
    if (!text.len)
974
0
        return;
975
976
0
    bstr dst = {0};
977
978
0
    while (text.len) {
979
0
        if (*text.start == '{') {
980
0
            bstr_xappend(NULL, &dst, bstr0("\\{"));
981
0
            text = bstr_cut(text, 1);
982
0
        } else if (*text.start == '\\') {
983
0
            bstr_xappend(NULL, &dst, bstr0("\\"));
984
            // Break ASS escapes with U+2060 WORD JOINER
985
0
            mp_append_utf8_bstr(NULL, &dst, 0x2060);
986
0
            text = bstr_cut(text, 1);
987
0
        }
988
989
0
        int i = bstrcspn(text, "{\\");
990
0
        bstr_xappend(NULL, &dst, (bstr){text.start, i});
991
0
        text = bstr_cut(text, i);
992
0
    }
993
994
0
    if (!dst.start)
995
0
        return;
996
997
0
    int n = ass_alloc_event(track);
998
0
    ASS_Event *event = track->events + n;
999
0
    event->Start = 0;
1000
0
    event->Duration = INT_MAX;
1001
0
    event->Style = track->default_style;
1002
0
    event->Text = strdup(dst.start);
1003
1004
0
    talloc_free(dst.start);
1005
0
}
1006
1007
static void reset(struct sd *sd)
1008
0
{
1009
0
    struct sd_ass_priv *ctx = sd->priv;
1010
0
    if (sd->opts->sub_clear_on_seek || ctx->clear_once) {
1011
0
        ass_flush_events(ctx->ass_track);
1012
0
        ctx->num_seen_packets = 0;
1013
0
        sd->preload_ok = false;
1014
0
        ctx->clear_once = false;
1015
0
    }
1016
0
    if (ctx->converter)
1017
0
        lavc_conv_reset(ctx->converter);
1018
0
}
1019
1020
static void uninit(struct sd *sd)
1021
0
{
1022
0
    struct sd_ass_priv *ctx = sd->priv;
1023
1024
0
    filters_destroy(sd);
1025
0
    if (ctx->converter)
1026
0
        lavc_conv_uninit(ctx->converter);
1027
0
    assobjects_destroy(sd);
1028
0
    talloc_free(ctx->copy_cache);
1029
0
}
1030
1031
static struct sub_lines *get_lines(struct sd *sd)
1032
0
{
1033
0
    struct sd_ass_priv *ctx = sd->priv;
1034
0
    ASS_Track *track = ctx->ass_track;
1035
0
    struct sub_lines *res = talloc_zero(NULL, struct sub_lines);
1036
1037
0
    for (int i = 0; i < track->n_events; i++) {
1038
0
        ASS_Event *event = &track->events[i];
1039
0
        if (!event->Text)
1040
0
            continue;
1041
1042
0
        char *plain = NULL;
1043
0
        bstr result = sd_ass_to_plaintext(&plain, event->Text);
1044
1045
        // ASS subtitle lines can have many empty lines after stripping tags,
1046
        // but empty lines are useful in LRC.
1047
0
        if (is_whitespace_only(result)) {
1048
0
            talloc_free(plain);
1049
0
            if (!strcmp(sd->codec->codec, "ass"))
1050
0
                continue;
1051
0
            plain = talloc_strdup(res, "");
1052
0
        } else {
1053
0
            talloc_steal(res, plain);
1054
0
        }
1055
1056
0
        struct sub_line line = {
1057
0
            .text  = plain,
1058
0
            .start = event->Start / 1000.0,
1059
0
            .end   = event->Duration == UNKNOWN_DURATION * 1000
1060
0
                         ? MP_NOPTS_VALUE
1061
0
                         : (event->Start + event->Duration) / 1000.0,
1062
0
        };
1063
0
        MP_TARRAY_APPEND(res, res->entries, res->num_entries, line);
1064
0
    }
1065
1066
0
    return res;
1067
0
}
1068
1069
static int control(struct sd *sd, enum sd_ctrl cmd, void *arg)
1070
0
{
1071
0
    struct sd_ass_priv *ctx = sd->priv;
1072
0
    switch (cmd) {
1073
0
    case SD_CTRL_SUB_STEP: {
1074
0
        double *a = arg;
1075
0
        long long ts = floor(a[0] * 1000.0 + 1e-6);
1076
0
        long long res = ass_step_sub(ctx->ass_track, ts, a[1]);
1077
0
        if (!res)
1078
0
            return false;
1079
        // Try to account for overlapping durations
1080
0
        a[0] += res / 1000.0 + SUB_SEEK_OFFSET;
1081
0
        return true;
1082
0
    }
1083
0
    case SD_CTRL_SET_ANIMATED_CHECK:
1084
0
        ctx->check_animated = *(bool *)arg;
1085
0
        return CONTROL_OK;
1086
0
    case SD_CTRL_RESET_SOFT:
1087
0
        ctx->clear_once = true;
1088
0
        reset(sd);
1089
0
        return CONTROL_OK;
1090
0
    case SD_CTRL_SET_VIDEO_PARAMS:
1091
0
        ctx->video_params = *(struct mp_image_params *)arg;
1092
0
        return CONTROL_OK;
1093
0
    case SD_CTRL_UPDATE_OPTS: {
1094
0
        uint64_t flags = *(uint64_t *)arg;
1095
0
        if (flags & UPDATE_SUB_FILT) {
1096
0
            filters_destroy(sd);
1097
0
            filters_init(sd);
1098
0
            ctx->clear_once = true; // allow reloading on seeks
1099
0
            reset(sd);
1100
0
        }
1101
0
        if (flags & UPDATE_SUB_HARD) {
1102
            // ass_track will be recreated, so clear duplicate cache
1103
0
            ctx->clear_once = true;
1104
0
            reset(sd);
1105
0
            assobjects_destroy(sd);
1106
0
            assobjects_init(sd);
1107
0
        }
1108
0
        ctx->ass_configured = false; // ass always needs to be reconfigured
1109
0
        return CONTROL_OK;
1110
0
    }
1111
0
    default:
1112
0
        return CONTROL_UNKNOWN;
1113
0
    }
1114
0
}
1115
1116
const struct sd_functions sd_ass = {
1117
    .name = "ass",
1118
    .accept_packets_in_advance = true,
1119
    .init = init,
1120
    .decode = decode,
1121
    .get_bitmaps = get_bitmaps,
1122
    .get_text = get_text,
1123
    .get_times = get_times,
1124
    .get_lines = get_lines,
1125
    .control = control,
1126
    .reset = reset,
1127
    .select = enable_output,
1128
    .uninit = uninit,
1129
};
1130
1131
// Disgusting hack for (xy-)vsfilter color compatibility.
1132
static void mangle_colors(struct sd *sd, struct sub_bitmaps *parts)
1133
0
{
1134
0
    struct mp_subtitle_opts *opts = sd->opts;
1135
0
    struct sd_ass_priv *ctx = sd->priv;
1136
0
    enum pl_color_system csp = 0;
1137
0
    enum pl_color_levels levels = 0;
1138
0
    if (opts->ass_vsfilter_color_compat == 0) // "no"
1139
0
        return;
1140
0
    bool force_601 = opts->ass_vsfilter_color_compat == 3;
1141
0
    ASS_Track *track = ctx->ass_track;
1142
0
    static const int ass_csp[] = {
1143
0
        [YCBCR_BT601_TV]        = PL_COLOR_SYSTEM_BT_601,
1144
0
        [YCBCR_BT601_PC]        = PL_COLOR_SYSTEM_BT_601,
1145
0
        [YCBCR_BT709_TV]        = PL_COLOR_SYSTEM_BT_709,
1146
0
        [YCBCR_BT709_PC]        = PL_COLOR_SYSTEM_BT_709,
1147
0
        [YCBCR_SMPTE240M_TV]    = PL_COLOR_SYSTEM_SMPTE_240M,
1148
0
        [YCBCR_SMPTE240M_PC]    = PL_COLOR_SYSTEM_SMPTE_240M,
1149
0
    };
1150
0
    static const int ass_levels[] = {
1151
0
        [YCBCR_BT601_TV]        = PL_COLOR_LEVELS_LIMITED,
1152
0
        [YCBCR_BT601_PC]        = PL_COLOR_LEVELS_FULL,
1153
0
        [YCBCR_BT709_TV]        = PL_COLOR_LEVELS_LIMITED,
1154
0
        [YCBCR_BT709_PC]        = PL_COLOR_LEVELS_FULL,
1155
0
        [YCBCR_SMPTE240M_TV]    = PL_COLOR_LEVELS_LIMITED,
1156
0
        [YCBCR_SMPTE240M_PC]    = PL_COLOR_LEVELS_FULL,
1157
0
    };
1158
0
    int trackcsp = track->YCbCrMatrix;
1159
0
    if (force_601)
1160
0
        trackcsp = YCBCR_BT601_TV;
1161
    // NONE is a bit random, but the intention is: don't modify colors.
1162
0
    if (trackcsp == YCBCR_NONE)
1163
0
        return;
1164
0
    if (trackcsp < MP_ARRAY_SIZE(ass_csp))
1165
0
        csp = ass_csp[trackcsp];
1166
0
    if (trackcsp <  MP_ARRAY_SIZE(ass_levels))
1167
0
        levels = ass_levels[trackcsp];
1168
0
    if (trackcsp == YCBCR_DEFAULT) {
1169
0
        csp = PL_COLOR_SYSTEM_BT_601;
1170
0
        levels = PL_COLOR_LEVELS_LIMITED;
1171
0
    }
1172
    // Unknown colorspace (either YCBCR_UNKNOWN, or a valid value unknown to us)
1173
0
    if (!csp || !levels)
1174
0
        return;
1175
1176
0
    struct mp_image_params params = ctx->video_params;
1177
1178
0
    if (force_601) {
1179
0
        params.repr = (struct pl_color_repr){
1180
0
            .sys = PL_COLOR_SYSTEM_BT_709,
1181
0
            .levels = PL_COLOR_LEVELS_LIMITED,
1182
0
        };
1183
0
    }
1184
1185
0
    if ((csp == params.repr.sys && levels == params.repr.levels) ||
1186
0
            params.repr.sys == PL_COLOR_SYSTEM_RGB) // Even VSFilter doesn't mangle on RGB video
1187
0
        return;
1188
1189
0
    bool basic_conv = params.repr.sys == PL_COLOR_SYSTEM_BT_709 &&
1190
0
                      params.repr.levels == PL_COLOR_LEVELS_LIMITED &&
1191
0
                      csp == PL_COLOR_SYSTEM_BT_601 &&
1192
0
                      levels == PL_COLOR_LEVELS_LIMITED;
1193
1194
    // With "basic", only do as much as needed for basic compatibility.
1195
0
    if (opts->ass_vsfilter_color_compat == 1 && !basic_conv)
1196
0
        return;
1197
1198
0
    if (params.repr.sys != ctx->last_params.repr.sys ||
1199
0
        params.repr.levels != ctx->last_params.repr.levels)
1200
0
    {
1201
0
        int msgl = basic_conv ? MSGL_V : MSGL_WARN;
1202
0
        ctx->last_params = params;
1203
0
        MP_MSG(sd, msgl, "mangling colors like vsfilter: "
1204
0
               "RGB -> %s %s -> %s %s -> RGB\n",
1205
0
               m_opt_choice_str(pl_csp_names, csp),
1206
0
               m_opt_choice_str(pl_csp_levels_names, levels),
1207
0
               m_opt_choice_str(pl_csp_names, params.repr.sys),
1208
0
               m_opt_choice_str(pl_csp_names, params.repr.levels));
1209
0
    }
1210
1211
    // Conversion that VSFilter would use
1212
0
    struct mp_csp_params vs_params = MP_CSP_PARAMS_DEFAULTS;
1213
0
    vs_params.repr.sys = csp;
1214
0
    vs_params.repr.levels = levels;
1215
0
    struct pl_transform3x3 vs_yuv2rgb;
1216
0
    mp_get_csp_matrix(&vs_params, &vs_yuv2rgb);
1217
0
    pl_transform3x3_invert(&vs_yuv2rgb);
1218
1219
    // Proper conversion to RGB
1220
0
    struct mp_csp_params rgb_params = MP_CSP_PARAMS_DEFAULTS;
1221
0
    rgb_params.repr = params.repr;
1222
0
    rgb_params.color = params.color;
1223
0
    struct pl_transform3x3 vs2rgb;
1224
0
    mp_get_csp_matrix(&rgb_params, &vs2rgb);
1225
1226
0
    for (int n = 0; n < parts->num_parts; n++) {
1227
0
        struct sub_bitmap *sb = &parts->parts[n];
1228
0
        uint32_t color = sb->libass.color;
1229
0
        int r = (color >> 24u) & 0xff;
1230
0
        int g = (color >> 16u) & 0xff;
1231
0
        int b = (color >>  8u) & 0xff;
1232
0
        int a = 0xff - (color & 0xff);
1233
0
        int rgb[3] = {r, g, b}, yuv[3];
1234
0
        mp_map_fixp_color(&vs_yuv2rgb, 8, rgb, 8, yuv);
1235
0
        mp_map_fixp_color(&vs2rgb, 8, yuv, 8, rgb);
1236
0
        sb->libass.color = MP_ASS_RGBA(rgb[0], rgb[1], rgb[2], a);
1237
0
    }
1238
0
}
1239
1240
int sd_ass_fmt_offset(const char *evt_fmt)
1241
0
{
1242
    // "Text" is always last (as it's arbitrary content in buf), e.g. format:
1243
    // "Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
1244
0
    int n = 0;
1245
0
    while (evt_fmt && (evt_fmt = strchr(evt_fmt, ',')))
1246
0
         evt_fmt++, n++;
1247
0
    return n-1;  // buffer is without the format's Start/End, with ReadOrder
1248
0
}
1249
1250
bstr sd_ass_pkt_text(struct sd_filter *ft, struct demux_packet *pkt, int offset)
1251
0
{
1252
    // e.g. pkt->buffer ("4" is ReadOrder): "4,0,Default,,0,0,0,,fifth line"
1253
0
    bstr txt = {(char *)pkt->buffer, pkt->len}, t0 = txt;
1254
0
    while (offset-- > 0) {
1255
0
        int n = bstrchr(txt, ',');
1256
0
        if (n < 0) {  // shouldn't happen
1257
0
            MP_WARN(ft, "Malformed event '%.*s'\n", BSTR_P(t0));
1258
0
            return (bstr){NULL, 0};
1259
0
        }
1260
0
        txt = bstr_cut(txt, n+1);
1261
0
    }
1262
0
    return txt;
1263
0
}
1264
1265
bstr sd_ass_to_plaintext(char **out, const char *in)
1266
0
{
1267
0
    bstr b = {*out};
1268
0
    ass_to_plaintext(&b, in);
1269
0
    *out = b.start;
1270
0
    return b;
1271
0
}