summaryrefslogtreecommitdiffstats
path: root/libass/ass_directwrite.c
blob: 85857bd6ed30cf5e807ba0ec0071886590d3c63a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
/*
 * Copyright (C) 2015 Stephan Vedder <stephan.vedder@gmail.com>
 *
 * This file is part of libass.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#define COBJMACROS

#include "config.h"
#include "ass_compat.h"

#include <initguid.h>
#include <wchar.h>

#include "dwrite_c.h"

#include "ass_directwrite.h"
#include "ass_utils.h"

#define FALLBACK_DEFAULT_FONT L"Arial"

static const ASS_FontMapping font_substitutions[] = {
    {"sans-serif", "Arial"},
    {"serif", "Times New Roman"},
    {"monospace", "Courier New"}
};

typedef struct ASS_SharedHDC ASS_SharedHDC;

#if ASS_WINAPI_DESKTOP

struct ASS_SharedHDC {
    HDC hdc;
    unsigned ref_count;
};

static ASS_SharedHDC *hdc_retain(ASS_SharedHDC *shared_hdc)
{
    shared_hdc->ref_count++;
    return shared_hdc;
}

static void hdc_release(ASS_SharedHDC *shared_hdc)
{
    if (!--shared_hdc->ref_count) {
        DeleteDC(shared_hdc->hdc);
        free(shared_hdc);
    }
}

#endif

/*
 * The private data stored for every font, detected by this backend.
 */
typedef struct {
#if ASS_WINAPI_DESKTOP
    ASS_SharedHDC *shared_hdc;
#endif
    IDWriteFont *font;
    IDWriteFontFace *face;
    IDWriteFontFileStream *stream;
} FontPrivate;

typedef struct {
#if ASS_WINAPI_DESKTOP
    HMODULE directwrite_lib;
#endif
    IDWriteFactory *factory;
    IDWriteGdiInterop *gdi_interop;
} ProviderPrivate;

/**
 * Custom text renderer class for logging the fonts used. It does not
 * actually render anything or do anything apart from that.
 */

typedef struct FallbackLogTextRenderer {
    IDWriteTextRenderer iface;
    IDWriteTextRendererVtbl vtbl;
    IDWriteFactory *dw_factory;
    LONG ref_count;
} FallbackLogTextRenderer;

static HRESULT STDMETHODCALLTYPE FallbackLogTextRenderer_IsPixelSnappingDisabled(
    IDWriteTextRenderer *This,
    void* clientDrawingContext,
    BOOL* isDisabled
    )
{
    *isDisabled = true;
    return S_OK;
}

static HRESULT STDMETHODCALLTYPE FallbackLogTextRenderer_GetCurrentTransform(
    IDWriteTextRenderer *This,
    void* clientDrawingContext,
    DWRITE_MATRIX* transform
    )
{
    return E_NOTIMPL;
}

static HRESULT STDMETHODCALLTYPE FallbackLogTextRenderer_GetPixelsPerDip(
    IDWriteTextRenderer *This,
    void* clientDrawingContext,
    FLOAT* pixelsPerDip
    )
{
    return E_NOTIMPL;
}

static HRESULT STDMETHODCALLTYPE FallbackLogTextRenderer_DrawGlyphRun(
    IDWriteTextRenderer *This,
    void* clientDrawingContext,
    FLOAT baselineOriginX,
    FLOAT baselineOriginY,
    DWRITE_MEASURING_MODE measuringMode,
    DWRITE_GLYPH_RUN const* glyphRun,
    DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
    IUnknown* clientDrawingEffect
    )
{
    FallbackLogTextRenderer *this = (FallbackLogTextRenderer *)This;
    HRESULT hr;
    IDWriteFontCollection *font_coll = NULL;
    IDWriteFont **font = (IDWriteFont **)clientDrawingContext;

    hr = IDWriteFactory_GetSystemFontCollection(this->dw_factory, &font_coll, FALSE);
    if (FAILED(hr))
        return E_FAIL;

    hr = IDWriteFontCollection_GetFontFromFontFace(font_coll, glyphRun->fontFace,
                                                   font);
    if (FAILED(hr))
        return E_FAIL;

    return S_OK;
}

static HRESULT STDMETHODCALLTYPE FallbackLogTextRenderer_DrawUnderline(
    IDWriteTextRenderer *This,
    void* clientDrawingContext,
    FLOAT baselineOriginX,
    FLOAT baselineOriginY,
    DWRITE_UNDERLINE const* underline,
    IUnknown* clientDrawingEffect
    )
{
    return S_OK;
}

static HRESULT STDMETHODCALLTYPE FallbackLogTextRenderer_DrawStrikethrough(
    IDWriteTextRenderer *This,
    void* clientDrawingContext,
    FLOAT baselineOriginX,
    FLOAT baselineOriginY,
    DWRITE_STRIKETHROUGH const* strikethrough,
    IUnknown* clientDrawingEffect
    )
{
    return S_OK;
}

static HRESULT STDMETHODCALLTYPE FallbackLogTextRenderer_DrawInlineObject(
    IDWriteTextRenderer *This,
    void *clientDrawingContext,
    FLOAT originX,
    FLOAT originY,
    IDWriteInlineObject *inlineObject,
    BOOL isSideways,
    BOOL isRightToLeft,
    IUnknown *clientDrawingEffect
    )
{
    return S_OK;
}

// IUnknown methods

static ULONG STDMETHODCALLTYPE FallbackLogTextRenderer_AddRef(
    IDWriteTextRenderer *This
    )
{
    FallbackLogTextRenderer *this = (FallbackLogTextRenderer *)This;
    return InterlockedIncrement(&this->ref_count);
}

static ULONG STDMETHODCALLTYPE FallbackLogTextRenderer_Release(
    IDWriteTextRenderer *This
    )
{
    FallbackLogTextRenderer *this = (FallbackLogTextRenderer *)This;
    unsigned long new_count = InterlockedDecrement(&this->ref_count);
    if (new_count == 0) {
        free(this);
        return 0;
    }

    return new_count;
}

static HRESULT STDMETHODCALLTYPE FallbackLogTextRenderer_QueryInterface(
    IDWriteTextRenderer *This,
    REFIID riid,
    void **ppvObject
    )
{
    if (IsEqualGUID(riid, &IID_IDWriteTextRenderer)
        || IsEqualGUID(riid, &IID_IDWritePixelSnapping)
        || IsEqualGUID(riid, &IID_IUnknown)) {
        *ppvObject = This;
    } else {
        *ppvObject = NULL;
        return E_FAIL;
    }

    This->lpVtbl->AddRef(This);
    return S_OK;
}

static void init_FallbackLogTextRenderer(FallbackLogTextRenderer *r,
                                         IDWriteFactory *factory)
{
    *r = (FallbackLogTextRenderer) {
        .iface = {
            .lpVtbl = &r->vtbl,
        },
        .vtbl = {
            FallbackLogTextRenderer_QueryInterface,
            FallbackLogTextRenderer_AddRef,
            FallbackLogTextRenderer_Release,
            FallbackLogTextRenderer_IsPixelSnappingDisabled,
            FallbackLogTextRenderer_GetCurrentTransform,
            FallbackLogTextRenderer_GetPixelsPerDip,
            FallbackLogTextRenderer_DrawGlyphRun,
            FallbackLogTextRenderer_DrawUnderline,
            FallbackLogTextRenderer_DrawStrikethrough,
            FallbackLogTextRenderer_DrawInlineObject,
        },
        .dw_factory = factory,
    };
}

/*
 * This function is called whenever a font is accessed for the
 * first time. It will create a FontFace for metadata access and
 * memory reading, which will be stored within the private data.
 */
static bool init_font_private_face(FontPrivate *priv)
{
    HRESULT hr;
    IDWriteFontFace *face;

    if (priv->face != NULL)
        return true;

    hr = IDWriteFont_CreateFontFace(priv->font, &face);
    if (FAILED(hr) || !face)
        return false;

    priv->face = face;
    return true;
}

/*
 * This function is called whenever a font is used for the first
 * time. It will create a FontStream for memory reading, which
 * will be stored within the private data.
 */
static bool init_font_private_stream(FontPrivate *priv)
{
    HRESULT hr = S_OK;
    IDWriteFontFile *file = NULL;
    IDWriteFontFileStream *stream = NULL;
    IDWriteFontFileLoader *loader = NULL;
    UINT32 n_files = 1;
    const void *refKey = NULL;
    UINT32 keySize = 0;

    if (priv->stream != NULL)
        return true;

    if (!init_font_private_face(priv))
        return false;

    /* DirectWrite only supports one file per face */
    hr = IDWriteFontFace_GetFiles(priv->face, &n_files, &file);
    if (FAILED(hr) || !file)
        return false;

    hr = IDWriteFontFile_GetReferenceKey(file, &refKey, &keySize);
    if (FAILED(hr)) {
        IDWriteFontFile_Release(file);
        return false;
    }

    hr = IDWriteFontFile_GetLoader(file, &loader);
    if (FAILED(hr) || !loader) {
        IDWriteFontFile_Release(file);
        return false;
    }

    hr = IDWriteFontFileLoader_CreateStreamFromKey(loader, refKey, keySize, &stream);
    if (FAILED(hr) || !stream) {
        IDWriteFontFile_Release(file);
        return false;
    }

    priv->stream = stream;
    IDWriteFontFile_Release(file);

    return true;
}

/*
 * Read a specified part of a fontfile into memory.
 * If the font wasn't used before first creates a
 * FontStream and save it into the private data for later usage.
 * If the parameter "buf" is NULL libass wants to know the
 * size of the Fontfile
 */
static size_t get_data(void *data, unsigned char *buf, size_t offset,
                       size_t length)
{
    HRESULT hr = S_OK;
    FontPrivate *priv = (FontPrivate *) data;
    const void *fileBuf = NULL;
    void *fragContext = NULL;

    if (!init_font_private_stream(priv))
        return 0;

    if (buf == NULL) {
        UINT64 fileSize;
        hr = IDWriteFontFileStream_GetFileSize(priv->stream, &fileSize);
        if (FAILED(hr))
            return 0;

        return fileSize;
    }

    hr = IDWriteFontFileStream_ReadFileFragment(priv->stream, &fileBuf, offset,
                                                length, &fragContext);

    if (FAILED(hr) || !fileBuf)
        return 0;

    memcpy(buf, fileBuf, length);

    IDWriteFontFileStream_ReleaseFileFragment(priv->stream, fragContext);

    return length;
}

/*
 * Check whether the font contains PostScript outlines.
 */
static bool check_postscript(void *data)
{
    FontPrivate *priv = (FontPrivate *) data;

    if (!init_font_private_face(priv))
        return false;

    DWRITE_FONT_FACE_TYPE type = IDWriteFontFace_GetType(priv->face);
    return type == DWRITE_FONT_FACE_TYPE_CFF ||
           type == DWRITE_FONT_FACE_TYPE_RAW_CFF ||
           type == DWRITE_FONT_FACE_TYPE_TYPE1;
}

/*
 * Lazily return index of font. It requires the FontFace to be present, which is expensive to initialize.
 */
static unsigned get_font_index(void *data)
{
    FontPrivate *priv = (FontPrivate *)data;

    if (!init_font_private_face(priv))
        return 0;

    return IDWriteFontFace_GetIndex(priv->face);
}

/*
 * Check if the passed font has a specific unicode character.
 */
static bool check_glyph(void *data, uint32_t code)
{
    HRESULT hr = S_OK;
    FontPrivate *priv = (FontPrivate *) data;
    BOOL exists = FALSE;

    if (code == 0)
        return true;

    if (priv->font) {
        hr = IDWriteFont_HasCharacter(priv->font, code, &exists);
        if (FAILED(hr))
            return false;
    } else {
        uint16_t glyph_index;
        hr = IDWriteFontFace_GetGlyphIndices(priv->face, &code, 1, &glyph_index);
        if (FAILED(hr))
            return false;
        exists = !!glyph_index;
    }

    return exists;
}

/*
 * This will release the directwrite backend
 */
static void destroy_provider(void *priv)
{
    ProviderPrivate *provider_priv = (ProviderPrivate *)priv;
    provider_priv->gdi_interop->lpVtbl->Release(provider_priv->gdi_interop);
    provider_priv->factory->lpVtbl->Release(provider_priv->factory);
#if ASS_WINAPI_DESKTOP
    FreeLibrary(provider_priv->directwrite_lib);
#endif
    free(provider_priv);
}

/*
 * This will destroy a specific font and it's
 * Fontstream (in case it does exist)
 */

static void destroy_font(void *data)
{
    FontPrivate *priv = (FontPrivate *) data;

    if (priv->font != NULL)
        IDWriteFont_Release(priv->font);
    if (priv->face != NULL)
        IDWriteFontFace_Release(priv->face);
    if (priv->stream != NULL)
        IDWriteFontFileStream_Release(priv->stream);

#if ASS_WINAPI_DESKTOP
    hdc_release(priv->shared_hdc);
#endif

    free(priv);
}

static int encode_utf16(wchar_t *chars, uint32_t codepoint)
{
    if (codepoint < 0x10000) {
        chars[0] = codepoint;
        return 1;
    } else {
        chars[0] = (codepoint >> 10) + 0xD7C0;
        chars[1] = (codepoint & 0x3FF) + 0xDC00;
        return 2;
    }
}

static char *get_utf8_name(IDWriteLocalizedStrings *names, int k)
{
    wchar_t *temp_name = NULL;
    char *mbName = NULL;

    UINT32 length;
    HRESULT hr = IDWriteLocalizedStrings_GetStringLength(names, k, &length);
    if (FAILED(hr))
        goto cleanup;

    if (length >= (UINT32) -1 || length + (size_t) 1 > SIZE_MAX / sizeof(wchar_t))
        goto cleanup;

    temp_name = malloc((length + 1) * sizeof(wchar_t));
    if (!temp_name)
        goto cleanup;

    hr = IDWriteLocalizedStrings_GetString(names, k, temp_name, length + 1);
    if (FAILED(hr))
        goto cleanup;

    int size_needed =
        WideCharToMultiByte(CP_UTF8, 0, temp_name, -1, NULL, 0, NULL, NULL);
    if (!size_needed)
        goto cleanup;

    mbName = malloc(size_needed);
    if (!mbName)
        goto cleanup;

    WideCharToMultiByte(CP_UTF8, 0, temp_name, -1, mbName, size_needed, NULL, NULL);

cleanup:
    free(temp_name);
    return mbName;
}

static char *get_fallback(void *priv, ASS_Library *lib,
                          const char *base, uint32_t codepoint)
{
    HRESULT hr;
    ProviderPrivate *provider_priv = (ProviderPrivate *)priv;
    IDWriteFactory *dw_factory = provider_priv->factory;
    IDWriteTextFormat *text_format = NULL;
    IDWriteTextLayout *text_layout = NULL;
    FallbackLogTextRenderer renderer;

    init_FallbackLogTextRenderer(&renderer, dw_factory);

    hr = IDWriteFactory_CreateTextFormat(dw_factory, FALLBACK_DEFAULT_FONT, NULL,
            DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_STYLE_NORMAL,
            DWRITE_FONT_STRETCH_NORMAL, 1.0f, L"", &text_format);
    if (FAILED(hr)) {
        return NULL;
    }

    // Encode codepoint as UTF-16
    wchar_t char_string[2];
    int char_len = encode_utf16(char_string, codepoint);

    // Create a text_layout, a high-level text rendering facility, using
    // the given codepoint and dummy format.
    hr = IDWriteFactory_CreateTextLayout(dw_factory, char_string, char_len, text_format,
        0.0f, 0.0f, &text_layout);
    if (FAILED(hr)) {
        IDWriteTextFormat_Release(text_format);
        return NULL;
    }

    // Draw the layout with a dummy renderer, which logs the
    // font used and stores it.
    IDWriteFont *font = NULL;
    hr = IDWriteTextLayout_Draw(text_layout, &font, &renderer.iface, 0.0f, 0.0f);
    if (FAILED(hr) || font == NULL) {
        IDWriteTextLayout_Release(text_layout);
        IDWriteTextFormat_Release(text_format);
        return NULL;
    }

    // We're done with these now
    IDWriteTextLayout_Release(text_layout);
    IDWriteTextFormat_Release(text_format);

    // DirectWrite may not have found a valid fallback, so check that
    // the selected font actually has the requested glyph.
    BOOL exists = FALSE;
    if (codepoint > 0) {
        hr = IDWriteFont_HasCharacter(font, codepoint, &exists);
        if (FAILED(hr) || !exists) {
            IDWriteFont_Release(font);
            return NULL;
        }
    }

    // Now, just extract the first family name
    IDWriteLocalizedStrings *familyNames = NULL;
    hr = IDWriteFont_GetInformationalStrings(font,
            DWRITE_INFORMATIONAL_STRING_WIN32_FAMILY_NAMES,
            &familyNames, &exists);
    if (SUCCEEDED(hr) && !exists) {
        IDWriteFontFamily *fontFamily = NULL;
        hr = IDWriteFont_GetFontFamily(font, &fontFamily);
        if (SUCCEEDED(hr)) {
            hr = IDWriteFontFamily_GetFamilyNames(fontFamily, &familyNames);
            IDWriteFontFamily_Release(fontFamily);
        }
    }
    if (FAILED(hr)) {
        IDWriteFont_Release(font);
        return NULL;
    }

    char *family = get_utf8_name(familyNames, 0);

    IDWriteLocalizedStrings_Release(familyNames);
    IDWriteFont_Release(font);
    return family;
}

#define FONT_TYPE IDWriteFontFace3
#include "ass_directwrite_info_template.h"
#undef FONT_TYPE

#define FONT_TYPE IDWriteFont
#define FAMILY_AS_ARG
#include "ass_directwrite_info_template.h"
#undef FONT_TYPE
#undef FAMILY_AS_ARG

static void add_font_face(IDWriteFontFace *face, ASS_FontProvider *provider,
                          ASS_SharedHDC *shared_hdc,
                          IDWriteFontCollection *system_font_coll)
{
    ASS_FontProviderMetaData meta = {0};

    IDWriteFontFace3 *face3;
    HRESULT hr = IDWriteFontFace_QueryInterface(face, &IID_IDWriteFontFace3,
                                                (void **) &face3);
    if (SUCCEEDED(hr) && face3) {
        bool success = get_font_info_IDWriteFontFace3(face3, &meta);
        IDWriteFontFace3_Release(face3);
        if (!success)
            goto cleanup;
    } else if (system_font_coll) {
        IDWriteFont *font;
        hr = IDWriteFontCollection_GetFontFromFontFace(system_font_coll,
                                                       face, &font);
        if (SUCCEEDED(hr) && font) {
            bool success = get_font_info_IDWriteFont(font, NULL, &meta);
            IDWriteFont_Release(font);
            if (!success)
                goto cleanup;
        }
    }

    FontPrivate *font_priv = calloc(1, sizeof(*font_priv));
    if (!font_priv)
        goto cleanup;

    font_priv->face = face;
    face = NULL;

#if ASS_WINAPI_DESKTOP
    font_priv->shared_hdc = hdc_retain(shared_hdc);
#endif

    ass_font_provider_add_font(provider, &meta, NULL, 0, font_priv);

cleanup:
    free(meta.postscript_name);
    free(meta.extended_family);

    if (face)
        IDWriteFontFace_Release(face);
}

#if ASS_WINAPI_DESKTOP

struct font_enum_priv {
    ASS_FontProvider *provider;
    IDWriteGdiInterop *gdi_interop;
    ASS_SharedHDC *shared_hdc;
    IDWriteFontCollection *system_font_coll;
};

/*
 * Windows has three similar functions: EnumFonts, EnumFontFamilies
 * and EnumFontFamiliesEx, which were introduced at different times.
 * Each takes a callback, and the declared callback type is the same
 * for all three. However, the actual arguments passed to the callback
 * have also changed over time. Some changes match the introduction
 * of new EnumFont... variants, and some don't. Documentation has
 * changed over the years, too, so it can be hard to figure out what
 * types, and when, are safe for the callback to take.
 *
 * In the header files, FONTENUMPROC is declared to take:
 *     CONST LOGFONT *, CONST TEXTMETRIC *
 * These are the baseline structs dating back to 16-bit Windows EnumFont.
 *
 * As of 2021, current versions of Microsoft's docs
 * for the EnumFontFamiliesEx callback use the same:
 *     const LOGFONT *, const TEXTMETRIC *
 * and for the EnumFontFamilies callback use:
 *     ENUMLOGFONT *, NEWTEXTMETRIC *
 * and mention that the first "can be cast as" ENUMLOGFONTEX or ENUMLOGFONTEXDV
 * while the second "can be an ENUMTEXTMETRIC structure" but for
 * non-TrueType fonts "is a pointer to a TEXTMETRIC structure".
 *
 * Docs from the 2000s (which include Win95/98/Me/NT/2000/XP details) use
 *     ENUMLOGFONTEX *, NEWTEXTMETRICEX *
 * in the EnumFontFamiliesEx callback's definition:
 *     https://web.archive.org/web/20050907052149
 *         /http://msdn.microsoft.com/library/en-us/gdi/fontext_9rmr.asp
 * and highlight these two extended struct types as advantages over
 * the EnumFontFamilies callback, suggesting that the actual arguments
 * to the EnumFontFamiliesEx callback have always been these two extended
 * structs. This is also reflected in the callback's parameter names
 * (which have stayed unchanged in the current docs).
 * EnumFontFamiliesEx itself was added in Windows NT 4.0 and 95.
 *
 * Similarly, the EnumFontFamilies callback's parameter names support
 * the idea that they have always used ENUMLOGFONT and NEWTEXTMETRIC.
 *
 * It seems the extra fields in NEWTEXTMETRIC[EX] compared to TEXTMETRIC
 * are merely zero-filled when they are irrelevant, rather than nonexistent
 * or inaccessible. This is further supported by the fact the later-still
 * struct ENUMTEXTMETRIC extends NEWTEXTMETRICEX even though the former
 * is/was (upon introduction) relevant only to PostScript fonts
 * while the latter is (supposedly) relevant only to TrueType fonts.
 *
 * Docs from the 2000s for ENUMLOGFONTEXDV and ENUMTEXTMETRIC:
 *     https://web.archive.org/web/20050306200105
 *         /http://msdn.microsoft.com/library/en-us/gdi/fontext_15gy.asp
 * seem to assert that the callback receives these two further-extended
 * structs *if and only if* running on Windows 2000 or newer.
 * We don't need them, but if we did, we'd have to check (or assume)
 * Windows version, because this extension does not seem to have
 * an associated feature check. Moreover, these structs are given
 * to the callbacks of all three EnumFont... function variants.
 * So even EnumFonts actually uses the extended structs in 21st-century
 * Windows, but the declared callback type can no longer be changed
 * without breaking existing C++ code due to its strongly-typed pointers.
 * When targeting modern Windows, though, it seems safe for consumer
 * code to take the newest structs and cast the function pointer
 * to the declared callback type.
 */
static int CALLBACK font_enum_proc(const ENUMLOGFONTW *lpelf,
                                   const NEWTEXTMETRICW *lpntm,
                                   DWORD FontType, LPARAM lParam)
{
    struct font_enum_priv *priv = (struct font_enum_priv *) lParam;
    HFONT hFont = NULL;
    HRESULT hr;

    if (FontType & RASTER_FONTTYPE)
        goto cleanup;

    LOGFONTW lf = lpelf->elfLogFont;
    // lf.lfFaceName currently holds the font family name.
    // The family may contain several fonts with equal numerical parameters
    // but distinct full names. If we pass lf to CreateFontIndirect as is,
    // we will miss this variety and merely get the same one font multiple
    // times. Try to increase our chances of seeing all the right fonts
    // by replacing the family name by the full name. There's some chance
    // that this in turn selects some *other* family's fonts and misses
    // the requested family, but we would rather take this chance than
    // add every font twice (via the family name and via the full name).
    // lfFaceName can hold up to LF_FACESIZE wchars; truncate longer names.
    wcsncpy(lf.lfFaceName, lpelf->elfFullName, LF_FACESIZE - 1);
    lf.lfFaceName[LF_FACESIZE - 1] = L'\0';

    hFont = CreateFontIndirectW(&lf);
    if (!hFont)
        goto cleanup;

    HDC hdc = priv->shared_hdc->hdc;
    if (!SelectObject(hdc, hFont))
        goto cleanup;

    wchar_t selected_name[LF_FACESIZE];
    if (!GetTextFaceW(hdc, LF_FACESIZE, selected_name))
        goto cleanup;
    if (_wcsnicmp(selected_name, lf.lfFaceName, LF_FACESIZE)) {
        // A different font was selected. This can happen if the requested
        // name is subject to charset-specific font substitution while
        // EnumFont... enumerates additional charsets contained in the font.
        // Alternatively, the font may have disappeared in the meantime.
        // Either way, there's no use looking at this font any further.
        goto cleanup;
    }

    // For single-font files, we could also use GetFontData, but for font
    // collection files, GDI does not expose the current font index.
    // CreateFontFaceFromHdc is able to find it out using a private API;
    // and it may also be more efficient if it doesn't copy the data.
    // The downside is that we must keep the HDC alive, at least on Windows 7,
    // to prevent the font from being deleted and breaking the IDWriteFontFace.
    IDWriteFontFace *face = NULL;
    hr =