Imported Upstream version 0.13.2+dsfg1

This commit is contained in:
Sebastian Ramacher 2016-02-24 00:16:51 +01:00
commit fb3990e9e5
2036 changed files with 287360 additions and 0 deletions

View file

@ -0,0 +1,88 @@
project(text-freetype2)
if(DISABLE_FREETYPE)
message(STATUS "Freetype text plugin disabled")
return()
endif()
find_package(Freetype QUIET)
if(NOT FREETYPE_FOUND AND ENABLE_FREETYPE)
message(FATAL_ERROR "Freetype library not found but set as enabled")
elseif(NOT FREETYPE_FOUND)
message(STATUS "Freetype library not found, Freetype text plugin disabled")
return()
endif()
if(WIN32)
set(text-freetype2_PLATFORM_SOURCES
find-font.c
find-font-windows.c)
elseif(APPLE)
find_package(Iconv QUIET)
if(NOT ICONV_FOUND AND ENABLE_FREETYPE)
message(FATAL_ERROR "Iconv library not found but plugin set as enabled")
elseif(NOT ICONV_FOUND)
message(STATUS "Iconv library not found, Freetype text plugin disabled")
return()
endif()
find_library(COCOA Cocoa)
set(text-freetype2_PLATFORM_SOURCES
find-font.c
find-font-cocoa.m
find-font-iconv.c)
include_directories(${COCOA}
${ICONV_INCLUDE_DIRS})
set(text-freetype2_PLATFORM_DEPS
${COCOA}
${ICONV_LIBRARIES})
set_source_files_properties(find-font-cocoa.m
PROPERTIES LANGUAGE C)
else()
find_package(Fontconfig QUIET)
if(NOT FONTCONFIG_FOUND AND ENABLE_FREETYPE)
message(FATAL_ERROR "fontconfig not found but plugin set as enabled")
elseif(NOT FONTCONFIG_FOUND)
message(STATUS "fontconfig not found, Freetype text plugin disabled")
return()
endif()
set(text-freetype2_PLATFORM_SOURCES
find-font-unix.c)
include_directories(${FONTCONFIG_INCLUDE_DIRS})
endif()
include_directories(${FREETYPE_INCLUDE_DIRS})
set(text-freetype2_SOURCES
find-font.h
obs-convenience.c
text-functionality.c
text-freetype2.c
obs-convenience.h
text-freetype2.h)
add_library(text-freetype2 MODULE
${text-freetype2_PLATFORM_SOURCES}
${text-freetype2_SOURCES})
target_link_libraries(text-freetype2
libobs
${text-freetype2_PLATFORM_DEPS}
${FREETYPE_LIBRARIES})
if(NOT WIN32)
if(FONTCONFIG_FOUND)
target_link_libraries(text-freetype2 ${FONTCONFIG_LIBRARIES})
endif()
endif()
if(APPLE AND ICONV_FOUND)
target_link_libraries(text-freetype2 ${ICONV_LIBRARIES})
endif()
install_obs_plugin_with_data(text-freetype2 data)

View file

@ -0,0 +1,14 @@
TextFreetype2="Text (FreeType 2)"
Font="Tipus de lletra"
Text="Text"
TextFile="Fitxer de text (UTF-8 o UTF-16)"
TextFileFilter="Fitxers de text (*.txt);;"
ChatLogMode="Mode de registre de xat (últimes 6 línies)"
Color1="Color 1"
Color2="Color 2"
Outline="Contorn"
DropShadow="Ombra"
ReadFromFile="Llegeix del fitxer"
CustomWidth="Amplada de text personalitzada"
WordWrap="Ajustament de línia"

View file

@ -0,0 +1,14 @@
TextFreetype2="Text (FreeType 2)"
Font="Písmo"
Text="Text"
TextFile="Textový soubor (UTF-8 nebo UTF-16)"
TextFileFilter="Textové soubory (*.txt);;"
ChatLogMode="Mód záznamu jako chat (posledních 6 řádků)"
Color1="Barva 1"
Color2="Barva 2"
Outline="Obrys"
DropShadow="Vrhat stín"
ReadFromFile="Číst ze souboru"
CustomWidth="Vlastní šířka textu"
WordWrap="Zalamování řádků"

View file

@ -0,0 +1,14 @@
TextFreetype2="Tekst (FreeType 2)"
Font="Skrifttype"
Text="Tekst"
TextFile="Tekstfil (UTF-8- eller UTF-16)"
TextFileFilter="Tekstfiler (*.txt);;"
ChatLogMode="Chat log tilstand (sidste 6 linjer)"
Color1="Farve 1"
Color2="Farve 2"
Outline="Skitse"
DropShadow="Drop Shadow"
ReadFromFile="Læse fra fil"
CustomWidth="Brugerdefineret tekstbredde"
WordWrap="Tekstombrydning"

View file

@ -0,0 +1,14 @@
TextFreetype2="Text (FreeType 2)"
Font="Schriftart"
Text="Text"
TextFile="Textdatei (UTF-8 oder UTF-16)"
TextFileFilter="Textdateien (*.txt);;"
ChatLogMode="Chat-Log-Modus (letzte 6 Zeilen)"
Color1="Farbe 1"
Color2="Farbe 2"
Outline="Umrandung"
DropShadow="Schlagschatten"
ReadFromFile="Aus Datei lesen"
CustomWidth="Benutzerdefinierte Textbreite"
WordWrap="Zeilenumbruch"

View file

@ -0,0 +1,13 @@
Font="Γραμματοσειρά"
Text="Κείμενο"
TextFile="Αρχείο κειμένου (UTF-8 ή UTF-16)"
TextFileFilter="Αρχεία Κειμένου (*.txt);;"
ChatLogMode="Λειτουργία καταγραφής συνομιλίας (τελευταίες 6 γραμμές)"
Color1="Χρώμα 1"
Color2="Χρώμα 2"
Outline="Περίγραμμα"
DropShadow="Προσπίπτουσα Σκιά"
ReadFromFile="Ανάγνωση από αρχείο"
CustomWidth="Προσαρμοσμένο πλάτος κειμένου"
WordWrap="Αναδίπλωση Λέξεων"

View file

@ -0,0 +1,13 @@
TextFreetype2="Text (FreeType 2)"
Font="Font"
Text="Text"
TextFile="Text File (UTF-8 or UTF-16)"
TextFileFilter="Text Files (*.txt);;"
ChatLogMode="Chat log mode (last 6 lines)"
Color1="Color 1"
Color2="Color 2"
Outline="Outline"
DropShadow="Drop Shadow"
ReadFromFile="Read from file"
CustomWidth="Custom text width"
WordWrap="Word Wrap"

View file

@ -0,0 +1,14 @@
TextFreetype2="Texto (FreeType 2)"
Font="Fuente"
Text="Texto"
TextFile="Archivo de texto (UTF-8 o UTF-16)"
TextFileFilter="Archivos de texto (*.txt);;"
ChatLogMode="Modo de registro de chat (últimas 6 líneas)"
Color1="Color 1"
Color2="Color 2"
Outline="Contorno"
DropShadow="Texto sombreado"
ReadFromFile="Leer desde archivo"
CustomWidth="Ancho de texto personalizado"
WordWrap="Ajuste de línea"

View file

@ -0,0 +1,14 @@
TextFreetype2="Idazkia (FreeType 2)"
Font="Hizkia"
Text="Idazkia"
TextFile="Idazki Agiria (UTF-8 edo UTF-16)"
TextFileFilter="Idazki Agiriak (*.txt);;"
ChatLogMode="Txat ohar modua (azken 6 lerroak)"
Color1="Margoa 1"
Color2="Margoa 2"
Outline="Ingurua"
DropShadow="Eror Itzala"
ReadFromFile="Irakurri agiritik"
CustomWidth="Norbere idazki zabalera"
WordWrap="Hitz Ingurapena"

View file

@ -0,0 +1,14 @@
TextFreetype2="Teksti"
Font="Kirjasin"
Text="Teksti"
TextFile="Tekstitiedosto (UTF-8 tai UTF-16)"
TextFileFilter="Tekstitiedostot (*.txt);;"
ChatLogMode="Keskustelun lokitila (6 viimeistä riviä)"
Color1="Väri 1"
Color2="Väri 2"
Outline="Reunaviiva"
DropShadow="Varjo"
ReadFromFile="Lue tiedostosta"
CustomWidth="Mukautettu tekstin pituus"
WordWrap="Sido"

View file

@ -0,0 +1,14 @@
TextFreetype2="Texte (FreeType 2)"
Font="Police"
Text="Texte"
TextFile="Fichier texte (UTF-8 ou UTF-16)"
TextFileFilter="Fichier texte (*.txt);;"
ChatLogMode="Mode log de chat (6 dernières lignes)"
Color1="Couleur 1"
Color2="Couleur 2"
Outline="Contour"
DropShadow="Ombre portée"
ReadFromFile="Lire depuis le fichier"
CustomWidth="Largeur du texte personnalisée"
WordWrap="Retour à la ligne"

View file

@ -0,0 +1,14 @@
TextFreetype2="Texto (FreeType 2)"
Font="Fonte"
Text="Texto"
TextFile="Ficheiro de texto (UTF-8 ou UTF-16)"
TextFileFilter="Ficheiros de texto (*.txt);;"
ChatLogMode="Modo de rexistro do chat (últimas 6 liñas)"
Color1="Cor 1"
Color2="Cor 2"
Outline="Contorno"
DropShadow="Texto sombreado"
ReadFromFile="Ler a partir dun ficheiro"
CustomWidth="Personalizar a largura do texto"
WordWrap="Axuste de liña"

View file

@ -0,0 +1,14 @@
TextFreetype2="Tekst (FreeType 2)"
Font="Font"
Text="Tekst"
TextFile="Tekstualni dokument (UTF-8 ili UTF-16)"
TextFileFilter="Tekstualne datoteke (*.txt);;"
ChatLogMode="Režim ćaskanja (poslednjih 6 redova)"
Color1="Boja 1"
Color2="Boja 2"
Outline="Ivice"
DropShadow="Sa senkom"
ReadFromFile="Učitaj iz datoteke"
CustomWidth="Specifična širina teksta"
WordWrap="Prelom reči"

View file

@ -0,0 +1,14 @@
TextFreetype2="Szöveg (FreeType 2)"
Font="Betűtípus"
Text="Szöveg"
TextFile="Szövegfájl (UTF-8 vagy UTF-16)"
TextFileFilter="Szövegfájlok (*.txt);;"
ChatLogMode="Beszélgetésnapló mód (utolsó 6 sor)"
Color1="Szín 1"
Color2="Szín 2"
Outline="Körvonal"
DropShadow="Vetett Árnyék"
ReadFromFile="Fájlból olvasni"
CustomWidth="Egyedi szövegszélesség"
WordWrap="Sortörés"

View file

@ -0,0 +1,14 @@
TextFreetype2="Testo (FreeType 2)"
Font="Carattere"
Text="Testo"
TextFile="File di testo (UTF-8 o UTF-16)"
TextFileFilter="File di testo (*.txt);;"
ChatLogMode="Modalità Chat log (ultime 6 linee)"
Color1="Colore 1"
Color2="Colore 2"
Outline="Contorno linea"
DropShadow="Ombra esterna"
ReadFromFile="Leggi da file"
CustomWidth="Larghezza testo personalizzato"
WordWrap="Word Wrap"

View file

@ -0,0 +1,14 @@
TextFreetype2="テキスト(FreeType 2)"
Font="フォント"
Text="テキスト"
TextFile="テキストファイル (UTF-8 または UTF-16)"
TextFileFilter="テキストファイル (*.txt);;"
ChatLogMode="チャットログモード最新6行"
Color1="色 1"
Color2="色 2"
Outline="輪郭"
DropShadow="影をつける"
ReadFromFile="ファイルからの読み取り"
CustomWidth="カスタムテキスト幅"
WordWrap="折り返し表示"

View file

@ -0,0 +1,14 @@
TextFreetype2="텍스트 (FreeType 2)"
Font="글꼴"
Text="텍스트"
TextFile="텍스트 파일(UTF-8 혹은 UTF-16)"
TextFileFilter="텍스트 파일 (*.txt);;"
ChatLogMode="대화 기록 모드 (최근 여섯 줄만 표시)"
Color1="색상 1"
Color2="색상 2"
Outline="외곽선"
DropShadow="그림자 삽입"
ReadFromFile="파일에서 읽기"
CustomWidth="임의 텍스트 너비"
WordWrap="자동 줄 바꿈"

View file

@ -0,0 +1,14 @@
TextFreetype2="Tekst (FreeType 2)"
Font="Skrifttype"
Text="Tekst"
TextFile="Tekstfil (UTF-8 eller UTF-16)"
TextFileFilter="Tekstfiler (*.txt);;"
ChatLogMode="Chatloggmodus (siste 6 linjer)"
Color1="Farge 1"
Color2="Farge 2"
Outline="Ytterlinje"
DropShadow="Tekstskygge"
ReadFromFile="Les fra fil"
CustomWidth="Egendefinert tekstbredde"
WordWrap="Tekstbryting"

View file

@ -0,0 +1,14 @@
TextFreetype2="Tekst (FreeType 2)"
Font="Lettertype"
Text="Tekst"
TextFile="Tekstbestand (UTF-8 of UTF-16)"
TextFileFilter="Tekstbestanden (*.txt);;"
ChatLogMode="Chatlog-modus (laatse 6 regels)"
Color1="Kleur 1"
Color2="Kleur 2"
Outline="Omlijning"
DropShadow="Slagschaduw"
ReadFromFile="Lees uit bestand"
CustomWidth="Aangepaste tekstbreedte"
WordWrap="Word Wrap"

View file

@ -0,0 +1,14 @@
TextFreetype2="Tekst (FreeType 2)"
Font="Czcionka"
Text="Tekst"
TextFile="Plik tekstowy (UTF-8 lub UTF-16)"
TextFileFilter="Pliki tekstowe (*.txt);;"
ChatLogMode="Tryb dziennika czatu (ostatnie 6 linii)"
Color1="Kolor 1"
Color2="Kolor 2"
Outline="Zarys linii"
DropShadow="Cień"
ReadFromFile="Czytaj z pliku"
CustomWidth="Własna szerokość tekstu"
WordWrap="Zawijanie wierszy"

View file

@ -0,0 +1,14 @@
TextFreetype2="Texto (FreeType 2)"
Font="Fonte"
Text="Texto"
TextFile="Arquivo de Texto (UTF-8 ou UTF-16)"
TextFileFilter="Arquivos de texto (*.txt);;"
ChatLogMode="Modo de Log de Mensagens (últimas 6 linhas)"
Color1="Cor 1"
Color2="Cor 2"
Outline="Contorno"
DropShadow="Sombra"
ReadFromFile="Ler de arquivo"
CustomWidth="Largura do texto personalizada"
WordWrap="Quebra de Linha"

View file

@ -0,0 +1,14 @@
TextFreetype2="Texto (FreeType 2)"
Font="Tipo de letra"
Text="Texto"
TextFile="Ficheiro de texto (UTF-8 ou UTF-16)"
TextFileFilter="Ficheiros de texto (*.txt);;"
ChatLogMode="Modo de registo do chat (últimas 6 linhas)"
Color1="Cor 1"
Color2="Cor 2"
Outline="Contorno"
DropShadow="Sombra projetada"
ReadFromFile="Ler do ficheiro"
CustomWidth="Largura do texto personalizada"
WordWrap="Quebra de linha"

View file

@ -0,0 +1,14 @@
TextFreetype2="Text (FreeType 2)"
Font="Font"
Text="Textul"
TextFile="Fişier text (UTF-8 sau UTF-16)"
TextFileFilter="Fișiere text (*.txt);;"
ChatLogMode="Modul jurnal chat (ultimele 6 rânduri)"
Color1="Culoarea 1"
Color2="Culoarea 2"
Outline="Contur"
DropShadow="Umbră text"
ReadFromFile="Citește din fișier"
CustomWidth="Lăţime text personalizată"
WordWrap="Word Wrap"

View file

@ -0,0 +1,14 @@
TextFreetype2="Текст (FreeType 2)"
Font="Шрифт"
Text="Текст"
TextFile="Текстовый файл (UTF-8 или UTF-16)"
TextFileFilter="Текстовые файлы (*.txt);;"
ChatLogMode="Режим чат-лога (последние 6 строк)"
Color1="Цвет 1"
Color2="Цвет 2"
Outline="Обводка"
DropShadow="Тень"
ReadFromFile="Чтение из файла"
CustomWidth="Пользовательская ширина текста"
WordWrap="Перенос слов"

View file

@ -0,0 +1,14 @@
TextFreetype2="Text (FreeType 2)"
Font="Písmo"
Text="Text"
TextFile="Textový súbor (UTF-8 alebo UTF-16)"
TextFileFilter="Textové súbory (*.txt);;"
ChatLogMode="Režim logovania chatu (posledných 6 riadkov)"
Color1="Farba 1"
Color2="Farba 2"
Outline="Obrys"
DropShadow="Tieň"
ReadFromFile="Čítať zo súboru"
CustomWidth="Vlastná šírka textu"
WordWrap="Zalamovanie textu"

View file

@ -0,0 +1,13 @@
Font="Pisava"
Text="Tekst"
TextFile="Besedilna datoteka (UTF-8 or UTF-16)"
TextFileFilter="Besedilne Datoteke (*.txt);;"
ChatLogMode="Način dnevnika klepeta (last 6 lines)"
Color1="Barva 1"
Color2="Barva 2"
Outline="Oris"
DropShadow="Odajaj senco"
ReadFromFile="Preberi iz datoteka"
CustomWidth="Širina poljubnega besedila"
WordWrap="Prelom besedila"

View file

@ -0,0 +1,14 @@
TextFreetype2="Tekst (FreeType 2)"
Font="Font"
Text="Tekst"
TextFile="Tekstualni dokument (UTF-8 ili UTF-16)"
TextFileFilter="Tekstualne datoteke (*.txt);;"
ChatLogMode="Režim ćaskanja (poslednjih 6 redova)"
Color1="Boja 1"
Color2="Boja 2"
Outline="Ivice"
DropShadow="Sa senkom"
ReadFromFile="Učitaj iz dokumenta"
CustomWidth="Specifična širina teksta"
WordWrap="Prelom reči"

View file

@ -0,0 +1,14 @@
TextFreetype2="Текст (FreeType 2)"
Font="Фонт"
Text="Текст"
TextFile="Текстуални документ (UTF-8 или UTF-16)"
TextFileFilter="Текстуалне датотеке (*.txt);;"
ChatLogMode="Режим ћаскања (последњих 6 редова)"
Color1="Боја 1"
Color2="Боја 2"
Outline="Ивице"
DropShadow="Са сенком"
ReadFromFile="Учитај из документа"
CustomWidth="Специфична ширина текста"
WordWrap="Прелом речи"

View file

@ -0,0 +1,13 @@
Font="Typsnitt"
Text="Text"
TextFile="Textfil (UTF-8 eller UTF-16)"
TextFileFilter="Textfiler (*.txt);;"
ChatLogMode="Chattloggsläge (sista 6 raderna)"
Color1="Färg 1"
Color2="Färg 2"
Outline="Kontur"
DropShadow="Skugga"
ReadFromFile="Läsa från fil"
CustomWidth="Anpassad textbredd"
WordWrap="Radbrytning"

View file

@ -0,0 +1,6 @@
Font="แบบอักษร"
Text="ข้อความ"
TextFileFilter="ไฟล์ข้อความ (*txt);;"
Color1="สี 1"
Color2="สี 2"

View file

@ -0,0 +1,14 @@
TextFreetype2="Metin (FreeType 2)"
Font="Yazı Tipi"
Text="Metin"
TextFile="Metin Dosyası (UTF-8 veya UTF-16)"
TextFileFilter="Metin dosyaları (*.txt);;"
ChatLogMode="Sohbet günlük modu (son 6 satır)"
Color1="Renk 1"
Color2="Renk 2"
Outline="Anahat"
DropShadow="Alt Gölge"
ReadFromFile="Dosyadan oku"
CustomWidth="Özel metin genişliği"
WordWrap="Sözcük Kaydırma"

View file

@ -0,0 +1,14 @@
TextFreetype2="文本 (FreeType 2)"
Font="字体"
Text="文本"
TextFile="文本文件(UTF-8 或 UTF-16)"
TextFileFilter="文本文件(*.txt);;"
ChatLogMode="聊天日志模式 (最后 6 行)"
Color1="颜色 1"
Color2="颜色 2"
Outline="大纲"
DropShadow="下拉阴影"
ReadFromFile="从文件读取"
CustomWidth="自定义文本宽度"
WordWrap="自动换行"

View file

@ -0,0 +1,13 @@
Font="字型"
Text="文字"
TextFile="文字檔案 UTF-8 或 UTF-16"
TextFileFilter="文字檔案 (*.txt);;"
ChatLogMode="聊天記錄模式(最多 6 行)"
Color1="顏色 1"
Color2="顏色 2"
Outline="外框"
DropShadow="陰影效果"
ReadFromFile="從檔案讀取"
CustomWidth="自定文字寬度"
WordWrap="自動換行"

View file

@ -0,0 +1,56 @@
uniform float4x4 ViewProj;
uniform float4x4 color_matrix;
uniform float3 color_range_min = {0.0, 0.0, 0.0};
uniform float3 color_range_max = {1.0, 1.0, 1.0};
uniform texture2d image;
sampler_state def_sampler {
Filter = Linear;
AddressU = Clamp;
AddressV = Clamp;
};
struct VertInOut {
float4 pos : POSITION;
float2 uv : TEXCOORD0;
float4 col : COLOR;
};
VertInOut VSDefault(VertInOut vert_in)
{
VertInOut vert_out;
vert_out.pos = mul(float4(vert_in.pos.xyz, 1.0), ViewProj);
vert_out.uv = vert_in.uv;
vert_out.col = vert_in.col;
return vert_out;
}
float4 PSDrawBare(VertInOut vert_in) : TARGET
{
return image.Sample(def_sampler, vert_in.uv) * vert_in.col;
}
float4 PSDrawMatrix(VertInOut vert_in) : TARGET
{
float4 yuv = image.Sample(def_sampler, vert_in.uv);
yuv.xyz = clamp(yuv.xyz, color_range_min, color_range_max);
return saturate(mul(float4(yuv.xyz, 1.0), color_matrix));
}
technique Draw
{
pass
{
vertex_shader = VSDefault(vert_in);
pixel_shader = PSDrawBare(vert_in);
}
}
technique DrawMatrix
{
pass
{
vertex_shader = VSDefault(vert_in);
pixel_shader = PSDrawMatrix(vert_in);
}
}

View file

@ -0,0 +1,114 @@
#include <util/darray.h>
#include <util/crc32.h>
#include "find-font.h"
#include "text-freetype2.h"
#import <Foundation/Foundation.h>
extern void save_font_list(void);
static inline void add_path_font(const char *path)
{
FT_Face face;
FT_Long idx = 0;
FT_Long max_faces = 1;
while (idx < max_faces) {
if (FT_New_Face(ft2_lib, path, idx, &face) != 0)
break;
build_font_path_info(face, idx++, path);
max_faces = face->num_faces;
FT_Done_Face(face);
}
}
static void add_path_fonts(NSFileManager *file_manager, NSString *path)
{
NSArray *files = NULL;
files = [file_manager contentsOfDirectoryAtPath:path error:nil];
for (NSString *file in files) {
NSString *full_path = [path stringByAppendingPathComponent:file];
add_path_font(full_path.fileSystemRepresentation);
}
}
void load_os_font_list(void)
{
@autoreleasepool {
BOOL is_dir;
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSLibraryDirectory, NSAllDomainsMask, true);
for (NSString *path in paths) {
NSFileManager *file_manager =
[NSFileManager defaultManager];
NSString *font_path =
[path stringByAppendingPathComponent:@"Fonts"];
bool folder_exists = [file_manager
fileExistsAtPath:font_path
isDirectory:&is_dir];
if (folder_exists && is_dir)
add_path_fonts(file_manager, font_path);
}
save_font_list();
}
}
static uint32_t add_font_checksum(uint32_t checksum, const char *path)
{
if (path && *path)
checksum = calc_crc32(checksum, path, strlen(path));
return checksum;
}
static uint32_t add_font_checksum_path(uint32_t checksum,
NSFileManager *file_manager, NSString *path)
{
NSArray *files = NULL;
files = [file_manager contentsOfDirectoryAtPath:path error:nil];
for (NSString *file in files) {
NSString *full_path = [path stringByAppendingPathComponent:file];
checksum = add_font_checksum(checksum,
full_path.fileSystemRepresentation);
}
return checksum;
}
uint32_t get_font_checksum(void)
{
uint32_t checksum = 0;
@autoreleasepool {
BOOL is_dir;
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSLibraryDirectory, NSAllDomainsMask, true);
for (NSString *path in paths) {
NSFileManager *file_manager =
[NSFileManager defaultManager];
NSString *font_path =
[path stringByAppendingPathComponent:@"Fonts"];
bool folder_exists = [file_manager
fileExistsAtPath:font_path
isDirectory:&is_dir];
if (folder_exists && is_dir)
checksum = add_font_checksum_path(checksum,
file_manager, font_path);
}
}
return checksum;
}

View file

@ -0,0 +1,164 @@
#include <iconv.h>
#include <errno.h>
#include "find-font.h"
struct mac_font_mapping {
unsigned short encoding_id;
unsigned short language_id;
const char *code_page;
};
#define TT_MAC_LANGID_ANY 0xFFFF
static const struct mac_font_mapping mac_codes[] = {
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_ENGLISH, "macintosh"},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_ICELANDIC,"x-mac-icelandic"},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_TURKISH, "x-mac-ce"},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_POLISH, "x-mac-ce"},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_ROMANIAN, "x-mac-romanian"},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_CZECH, "x-mac-ce"},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_SLOVAK, "x-mac-ce"},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_ANY, "macintosh"},
{TT_MAC_ID_JAPANESE, TT_MAC_LANGID_JAPANESE, "Shift_JIS"},
{TT_MAC_ID_JAPANESE, TT_MAC_LANGID_ANY, "Shift_JIS"},
{TT_MAC_ID_KOREAN, TT_MAC_LANGID_KOREAN, "EUC-KR"},
{TT_MAC_ID_KOREAN, TT_MAC_LANGID_ANY, "EUC-KR"},
{TT_MAC_ID_ARABIC, TT_MAC_LANGID_ARABIC, "x-mac-arabic"},
{TT_MAC_ID_ARABIC, TT_MAC_LANGID_URDU, "x-mac-farsi"},
{TT_MAC_ID_ARABIC, TT_MAC_LANGID_FARSI, "x-mac-farsi"},
{TT_MAC_ID_ARABIC, TT_MAC_LANGID_ANY, "x-mac-arabic"},
{TT_MAC_ID_HEBREW, TT_MAC_LANGID_HEBREW, "x-mac-hebrew"},
{TT_MAC_ID_HEBREW, TT_MAC_LANGID_ANY, "x-mac-hebrew"},
{TT_MAC_ID_GREEK, TT_MAC_LANGID_ANY, "x-mac-greek"},
{TT_MAC_ID_RUSSIAN, TT_MAC_LANGID_ANY, "x-mac-cyrillic"},
{TT_MAC_ID_DEVANAGARI, TT_MAC_LANGID_ANY, "x-mac-devanagari"},
{TT_MAC_ID_GURMUKHI, TT_MAC_LANGID_ANY, "x-mac-gurmukhi"},
{TT_MAC_ID_GUJARATI, TT_MAC_LANGID_ANY, "x-mac-gujarati"},
{
TT_MAC_ID_TRADITIONAL_CHINESE,
TT_MAC_LANGID_CHINESE_SIMPLIFIED,
"Big5"
},
{
TT_MAC_ID_TRADITIONAL_CHINESE,
TT_MAC_LANGID_ANY,
"Big5"
},
{
TT_MAC_ID_SIMPLIFIED_CHINESE,
TT_MAC_LANGID_CHINESE_SIMPLIFIED,
"GB2312"
},
{
TT_MAC_ID_SIMPLIFIED_CHINESE,
TT_MAC_LANGID_ANY,
"GB2312"
}
};
const char *iso_codes[] = {
"us-ascii",
NULL,
"iso-8859-1"
};
const char *ms_codes[] = {
"UTF-16BE",
"UTF-16BE",
"Shift_JIS",
NULL,
"Big5",
NULL,
NULL,
NULL,
NULL,
NULL,
"UTF-16BE"
};
static const size_t mac_code_count = sizeof(mac_codes) / sizeof(mac_codes[0]);
static const size_t iso_code_count = sizeof(iso_codes) / sizeof(iso_codes[0]);
static const size_t ms_code_count = sizeof(ms_codes) / sizeof(ms_codes[0]);
static const char *get_mac_code(uint16_t encoding_id, uint16_t language_id)
{
for (size_t i = 0; i < mac_code_count; i++) {
const struct mac_font_mapping *mac_code = &mac_codes[i];
if (mac_code->encoding_id == encoding_id &&
mac_code->language_id == language_id)
return mac_code->code_page;
}
return NULL;
}
static const char *get_code_page_for_font(uint16_t platform_id,
uint16_t encoding_id, uint16_t language_id)
{
const char *ret;
switch (platform_id) {
case TT_PLATFORM_APPLE_UNICODE:
return "UTF-16BE";
case TT_PLATFORM_MACINTOSH:
ret = get_mac_code(encoding_id, language_id);
if (!ret)
ret = get_mac_code(encoding_id, TT_MAC_LANGID_ANY);
return ret;
case TT_PLATFORM_ISO:
if (encoding_id < iso_code_count)
return iso_codes[encoding_id];
break;
case TT_PLATFORM_MICROSOFT:
if (encoding_id < ms_code_count)
return ms_codes[encoding_id];
break;
}
return NULL;
}
char *sfnt_name_to_utf8(FT_SfntName *sfnt_name)
{
const char *charset = get_code_page_for_font(sfnt_name->platform_id,
sfnt_name->encoding_id, sfnt_name->language_id);
char utf8[256];
char *conv_in, *conv_out;
size_t in_len, out_len;
if (!charset) {
blog(LOG_DEBUG, "invalid character set found, "
"platform_id: %d, encoding_id: %d, "
"language_id: %d",
sfnt_name->platform_id,
sfnt_name->encoding_id,
sfnt_name->language_id);
return NULL;
}
iconv_t ic = iconv_open("UTF-8", charset);
if (ic == (iconv_t)-1) {
blog(LOG_DEBUG, "couldn't intialize font code page "
"conversion: '%s' to 'utf-8': errno = %d",
charset, (int)errno);
return NULL;
}
conv_in = (char*)sfnt_name->string;
conv_out = utf8;
in_len = sfnt_name->string_len;
out_len = 256;
size_t n = iconv(ic, &conv_in, &in_len, &conv_out, &out_len);
if (n == (size_t)-1) {
blog(LOG_WARNING, "couldn't convert font name text: errno = %d",
(int)errno);
iconv_close(ic);
return NULL;
}
iconv_close(ic);
*conv_out = 0;
return bstrdup(utf8);
}

View file

@ -0,0 +1,82 @@
/*
Copyright (C) 2014 by Leonhard Oelke <leonhard@in-verted.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <fontconfig/fontconfig.h>
#include <util/base.h>
#include <util/dstr.h>
#include "find-font.h"
#include "text-freetype2.h"
void free_os_font_list(void)
{
}
bool load_cached_os_font_list(void)
{
return true;
}
void load_os_font_list(void)
{
}
const char *get_font_path(const char *family, uint16_t size, const char *style,
uint32_t flags, FT_Long *idx)
{
bool bold = !!(flags & OBS_FONT_BOLD);
bool italic = !!(flags & OBS_FONT_ITALIC);
FcPattern *pattern = FcPatternCreate();
FcPattern *match = NULL;
bool success = false;
FcResult match_result;
/* somewhat of a cheap hack */
static __thread char result[512];
FcPatternAddString(pattern, FC_FAMILY, (const FcChar8*)family);
FcPatternAddString(pattern, FC_STYLE, (const FcChar8*)style);
FcPatternAddInteger(pattern, FC_WEIGHT,
bold ? FC_WEIGHT_BOLD : FC_WEIGHT_REGULAR);
FcPatternAddInteger(pattern, FC_SLANT,
italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN);
FcPatternAddDouble(pattern, FC_SIZE, (double)size);
FcConfigSubstitute(NULL, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
match = FcFontMatch(NULL, pattern, &match_result);
if (match) {
FcChar8 *path = FcPatternFormat(match,
(const FcChar8*)"%{file}");
strncpy(result, (char*)path, 511);
FcStrFree(path);
int fc_index = 0;
FcPatternGetInteger(match, FC_INDEX, 1, &fc_index);
*idx = (FT_Long)fc_index;
FcPatternDestroy(match);
success = true;
} else {
blog(LOG_WARNING, "no matching font for '%s' found",
family);
}
FcPatternDestroy(pattern);
return success ? &result[0] : NULL;
}

View file

@ -0,0 +1,292 @@
#include <util/dstr.h>
#include <util/darray.h>
#include <util/crc32.h>
#include "find-font.h"
#include "text-freetype2.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
extern DARRAY(struct font_path_info) font_list;
extern void save_font_list(void);
struct mac_font_mapping {
unsigned short encoding_id;
unsigned short language_id;
unsigned int code_page;
};
#define TT_MAC_LANGID_ANY 0xFFFF
static const struct mac_font_mapping mac_codes[] = {
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_ENGLISH, 10000},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_ICELANDIC, 10079},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_TURKISH, 10081},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_POLISH, 10029},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_ROMANIAN, 10010},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_CZECH, 10029},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_SLOVAK, 10029},
{TT_MAC_ID_ROMAN, TT_MAC_LANGID_ANY, 10000},
{TT_MAC_ID_JAPANESE, TT_MAC_LANGID_JAPANESE, 932},
{TT_MAC_ID_JAPANESE, TT_MAC_LANGID_ANY, 932},
{TT_MAC_ID_TRADITIONAL_CHINESE,TT_MAC_LANGID_CHINESE_SIMPLIFIED, 950},
{TT_MAC_ID_TRADITIONAL_CHINESE,TT_MAC_LANGID_ANY, 950},
{TT_MAC_ID_KOREAN, TT_MAC_LANGID_KOREAN, 51949},
{TT_MAC_ID_KOREAN, TT_MAC_LANGID_ANY, 51949},
{TT_MAC_ID_ARABIC, TT_MAC_LANGID_ARABIC, 10004},
{TT_MAC_ID_ARABIC, TT_MAC_LANGID_URDU, 0},
{TT_MAC_ID_ARABIC, TT_MAC_LANGID_FARSI, 0},
{TT_MAC_ID_ARABIC, TT_MAC_LANGID_ANY, 10004},
{TT_MAC_ID_HEBREW, TT_MAC_LANGID_HEBREW, 10005},
{TT_MAC_ID_HEBREW, TT_MAC_LANGID_ANY, 10005},
{TT_MAC_ID_GREEK, TT_MAC_LANGID_ANY, 10006},
{TT_MAC_ID_RUSSIAN, TT_MAC_LANGID_ANY, 10007},
{TT_MAC_ID_DEVANAGARI, TT_MAC_LANGID_ANY, 0},
{TT_MAC_ID_GURMUKHI, TT_MAC_LANGID_ANY, 0},
{TT_MAC_ID_GUJARATI, TT_MAC_LANGID_ANY, 0},
{TT_MAC_ID_SIMPLIFIED_CHINESE, TT_MAC_LANGID_CHINESE_SIMPLIFIED, 936},
{TT_MAC_ID_SIMPLIFIED_CHINESE, TT_MAC_LANGID_ANY, 936}
};
unsigned int iso_codes[] = {
20127,
0,
28591
};
unsigned int ms_codes[] = {
1201,
1201,
932,
0,
950,
0,
0,
0,
0,
0,
1201
};
static const size_t mac_code_count = sizeof(mac_codes) / sizeof(mac_codes[0]);
static const size_t iso_code_count = sizeof(iso_codes) / sizeof(iso_codes[0]);
static const size_t ms_code_count = sizeof(ms_codes) / sizeof(ms_codes[0]);
static unsigned int get_mac_code(uint16_t encoding_id, uint16_t language_id)
{
for (size_t i = 0; i < mac_code_count; i++) {
const struct mac_font_mapping *mac_code = &mac_codes[i];
if (mac_code->encoding_id == encoding_id &&
mac_code->language_id == language_id)
return mac_code->code_page;
}
return 0;
}
static unsigned int get_code_page_for_font(uint16_t platform_id,
uint16_t encoding_id, uint16_t language_id)
{
unsigned int ret;
switch (platform_id) {
case TT_PLATFORM_APPLE_UNICODE:
return 1201;
case TT_PLATFORM_MACINTOSH:
ret = get_mac_code(encoding_id, language_id);
if (!ret)
ret = get_mac_code(encoding_id, TT_MAC_LANGID_ANY);
return ret;
case TT_PLATFORM_ISO:
if (encoding_id < iso_code_count)
return iso_codes[encoding_id];
break;
case TT_PLATFORM_MICROSOFT:
if (encoding_id < ms_code_count)
return ms_codes[encoding_id];
break;
}
return 0;
}
static char *wide_to_utf8(const wchar_t *str, size_t len)
{
size_t utf8_len;
char *utf8_str = NULL;
utf8_len = (size_t)WideCharToMultiByte(CP_UTF8, 0, str, (int)len,
NULL, 0, NULL, false);
if (utf8_len) {
utf8_str = bzalloc(utf8_len + 1);
utf8_len = (size_t)WideCharToMultiByte(CP_UTF8, 0,
str, (int)len,
utf8_str, (int)utf8_len + 1, NULL, false);
if (!utf8_len) {
bfree(utf8_str);
utf8_str = NULL;
}
}
return utf8_str;
}
static char *convert_utf16_be_to_utf8(FT_SfntName *sfnt_name)
{
size_t utf16_len = sfnt_name->string_len / 2;
wchar_t *utf16_str = malloc((utf16_len + 1) * sizeof(wchar_t));
char *utf8_str = NULL;
utf16_str[utf16_len] = 0;
/* convert to little endian */
for (size_t i = 0; i < utf16_len; i++) {
size_t pos = i * 2;
wchar_t ch = *(wchar_t *)&sfnt_name->string[pos];
utf16_str[i] = ((ch >> 8) & 0xFF) | ((ch << 8) & 0xFF00);
}
utf8_str = wide_to_utf8(utf16_str, utf16_len);
free(utf16_str);
return utf8_str;
}
char *sfnt_name_to_utf8(FT_SfntName *sfnt_name)
{
unsigned int code_page = get_code_page_for_font(
sfnt_name->platform_id,
sfnt_name->encoding_id,
sfnt_name->language_id);
char *utf8_str = NULL;
wchar_t *utf16_str;
size_t utf16_len;
if (code_page == 1201)
return convert_utf16_be_to_utf8(sfnt_name);
else if (code_page == 0)
return NULL;
utf16_len = MultiByteToWideChar(code_page, 0,
(char*)sfnt_name->string, sfnt_name->string_len,
NULL, 0);
if (utf16_len) {
utf16_str = malloc((utf16_len + 1) * sizeof(wchar_t));
utf16_len = MultiByteToWideChar(code_page, 0,
(char*)sfnt_name->string, sfnt_name->string_len,
utf16_str, (int)utf16_len);
if (utf16_len) {
utf16_str[utf16_len] = 0;
utf8_str = wide_to_utf8(utf16_str, utf16_len);
}
free(utf16_str);
}
return utf8_str;
}
uint32_t get_font_checksum(void)
{
uint32_t checksum = 0;
struct dstr path = {0};
HANDLE handle;
WIN32_FIND_DATAA wfd;
dstr_reserve(&path, MAX_PATH);
HRESULT res = SHGetFolderPathA(NULL, CSIDL_FONTS, NULL,
SHGFP_TYPE_CURRENT, path.array);
if (res != S_OK) {
blog(LOG_WARNING, "Error finding windows font folder");
return 0;
}
path.len = strlen(path.array);
dstr_cat(&path, "\\*.*");
handle = FindFirstFileA(path.array, &wfd);
if (handle == INVALID_HANDLE_VALUE)
goto free_string;
dstr_resize(&path, path.len - 4);
do {
checksum = calc_crc32(checksum, &wfd.ftLastWriteTime,
sizeof(FILETIME));
checksum = calc_crc32(checksum, wfd.cFileName,
strlen(wfd.cFileName));
} while (FindNextFileA(handle, &wfd));
FindClose(handle);
free_string:
dstr_free(&path);
return checksum;
}
void load_os_font_list(void)
{
struct dstr path = {0};
HANDLE handle;
WIN32_FIND_DATAA wfd;
dstr_reserve(&path, MAX_PATH);
HRESULT res = SHGetFolderPathA(NULL, CSIDL_FONTS, NULL,
SHGFP_TYPE_CURRENT, path.array);
if (res != S_OK) {
blog(LOG_WARNING, "Error finding windows font folder");
return;
}
path.len = strlen(path.array);
dstr_cat(&path, "\\*.*");
handle = FindFirstFileA(path.array, &wfd);
if (handle == INVALID_HANDLE_VALUE)
goto free_string;
dstr_resize(&path, path.len - 4);
do {
struct dstr full_path = {0};
FT_Face face;
FT_Long idx = 0;
FT_Long max_faces = 1;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
continue;
dstr_copy_dstr(&full_path, &path);
dstr_cat(&full_path, "\\");
dstr_cat(&full_path, wfd.cFileName);
while (idx < max_faces) {
FT_Error ret = FT_New_Face(ft2_lib, full_path.array,
idx, &face);
if (ret != 0)
break;
build_font_path_info(face, idx++, full_path.array);
max_faces = face->num_faces;
FT_Done_Face(face);
}
dstr_free(&full_path);
} while (FindNextFileA(handle, &wfd));
FindClose(handle);
save_font_list();
free_string:
dstr_free(&path);
}

View file

@ -0,0 +1,399 @@
#include <util/file-serializer.h>
#include <ctype.h>
#include <time.h>
#include <obs-module.h>
#include "find-font.h"
DARRAY(struct font_path_info) font_list;
static inline bool read_data(struct serializer *s, void *data, size_t size)
{
return s_read(s, data, size) == size;
}
static inline bool write_data(struct serializer *s, const void *data,
size_t size)
{
return s_write(s, data, size) == size;
}
#define read_var(s, data) read_data(s, &data, sizeof(data))
#define write_var(s, data) write_data(s, &data, sizeof(data))
static bool read_str(struct serializer *s, char **p_str)
{
uint32_t size;
char *str;
if (!read_var(s, size))
return false;
str = bmalloc(size + 1);
if (size && !read_data(s, str, size)) {
bfree(str);
return false;
}
str[size] = 0;
*p_str = str;
return true;
}
static bool write_str(struct serializer *s, const char *str)
{
uint32_t size = (uint32_t)(str ? strlen(str) : 0);
if (!write_var(s, size))
return false;
if (size && !write_data(s, str, size))
return false;
return true;
}
static bool load_cached_font_list(struct serializer *s)
{
bool success = true;
int count;
success = read_var(s, count);
if (!success) return false;
da_init(font_list);
da_resize(font_list, count);
#define do_read(var) \
success = read_var(s, var); \
if (!success) break
for (int i = 0; i < count; i++) {
struct font_path_info *info = &font_list.array[i];
success = read_str(s, &info->face_and_style);
if (!success) break;
do_read(info->full_len);
do_read(info->face_len);
do_read(info->is_bitmap);
do_read(info->num_sizes);
info->sizes = bmalloc(sizeof(int) * info->num_sizes);
success = read_data(s, info->sizes,
sizeof(int) * info->num_sizes);
if (!success) break;
do_read(info->bold);
success = read_str(s, &info->path);
if (!success) break;
do_read(info->italic);
do_read(info->index);
}
#undef do_read
if (!success) {
free_os_font_list();
return false;
}
return true;
}
extern uint32_t get_font_checksum();
static const uint32_t font_cache_ver = 1;
bool load_cached_os_font_list(void)
{
char *file_name = obs_module_config_path("font_data.bin");
uint32_t old_checksum;
uint32_t new_checksum;
struct serializer s;
uint32_t ver;
bool success;
success = file_input_serializer_init(&s, file_name);
bfree(file_name);
if (!success)
return false;
success = read_data(&s, &ver, sizeof(ver));
if (!success || ver != font_cache_ver) {
success = false;
goto finish;
}
success = s_read(&s, &old_checksum, sizeof(old_checksum));
new_checksum = get_font_checksum();
if (!success || old_checksum != new_checksum) {
success = false;
goto finish;
}
success = load_cached_font_list(&s);
finish:
file_input_serializer_free(&s);
return success;
}
void save_font_list(void)
{
char *file_name = obs_module_config_path("font_data.bin");
uint32_t font_checksum = get_font_checksum();
int font_count = (int)font_list.num;
struct serializer s;
bool success = false;
if (font_checksum)
success = file_output_serializer_init_safe(&s, file_name,
"tmp");
bfree(file_name);
if (!success)
return;
success = write_var(&s, font_cache_ver);
if (!success) return;
success = write_var(&s, font_checksum);
if (!success) return;
success = write_var(&s, font_count);
if (!success) return;
#define do_write(var) \
success = write_var(&s, var); \
if (!success) break
for (size_t i = 0; i < font_list.num; i++) {
struct font_path_info *info = &font_list.array[i];
success = write_str(&s, info->face_and_style);
if (!success) break;
do_write(info->full_len);
do_write(info->face_len);
do_write(info->is_bitmap);
do_write(info->num_sizes);
success = write_data(&s, info->sizes,
sizeof(int) * info->num_sizes);
if (!success) break;
do_write(info->bold);
success = write_str(&s, info->path);
if (!success) break;
do_write(info->italic);
do_write(info->index);
}
#undef do_write
file_output_serializer_free(&s);
}
static void create_bitmap_sizes(struct font_path_info *info, FT_Face face)
{
DARRAY(int) sizes;
if (!info->is_bitmap) {
info->num_sizes = 0;
info->sizes = NULL;
return;
}
da_init(sizes);
da_reserve(sizes, face->num_fixed_sizes);
for (int i = 0; i < face->num_fixed_sizes; i++) {
int val = face->available_sizes[i].size >> 6;
da_push_back(sizes, &val);
}
info->sizes = sizes.array;
info->num_sizes = (uint32_t)face->num_fixed_sizes;
}
static void add_font_path(FT_Face face,
FT_Long idx,
const char *family_in,
const char *style_in,
const char *path)
{
struct dstr face_and_style = {0};
struct font_path_info info;
if (!family_in || !path)
return;
dstr_copy(&face_and_style, family_in);
if (face->style_name) {
struct dstr style = {0};
dstr_copy(&style, style_in);
dstr_replace(&style, "Bold", "");
dstr_replace(&style, "Italic", "");
dstr_replace(&style, " ", " ");
dstr_depad(&style);
if (!dstr_is_empty(&style)) {
dstr_cat(&face_and_style, " ");
dstr_cat_dstr(&face_and_style, &style);
}
dstr_free(&style);
}
info.face_and_style = face_and_style.array;
info.full_len = (uint32_t)face_and_style.len;
info.face_len = (uint32_t)strlen(family_in);
info.is_bitmap = !!(face->face_flags & FT_FACE_FLAG_FIXED_SIZES);
info.bold = !!(face->style_flags & FT_STYLE_FLAG_BOLD);
info.italic = !!(face->style_flags & FT_STYLE_FLAG_ITALIC);
info.index = idx;
info.path = bstrdup(path);
create_bitmap_sizes(&info, face);
da_push_back(font_list, &info);
/*blog(LOG_DEBUG, "name: %s\n\tstyle: %s\n\tpath: %s\n",
family_in,
style_in,
path);*/
}
void build_font_path_info(FT_Face face, FT_Long idx, const char *path)
{
FT_UInt num_names = FT_Get_Sfnt_Name_Count(face);
DARRAY(char*) family_names;
da_init(family_names);
da_push_back(family_names, &face->family_name);
for (FT_UInt i = 0; i < num_names; i++) {
FT_SfntName name;
char *family;
FT_Error ret = FT_Get_Sfnt_Name(face, i, &name);
if (ret != 0 || name.name_id != TT_NAME_ID_FONT_FAMILY)
continue;
family = sfnt_name_to_utf8(&name);
if (!family)
continue;
for (size_t i = 0; i < family_names.num; i++) {
if (astrcmpi(family_names.array[i], family) == 0) {
bfree(family);
family = NULL;
break;
}
}
if (family)
da_push_back(family_names, &family);
}
for (size_t i = 0; i < family_names.num; i++) {
add_font_path(face, idx, family_names.array[i],
face->style_name, path);
/* first item isn't our allocation */
if (i > 0)
bfree(family_names.array[i]);
}
da_free(family_names);
}
void free_os_font_list(void)
{
for (size_t i = 0; i < font_list.num; i++)
font_path_info_free(font_list.array + i);
da_free(font_list);
}
static inline size_t get_rating(struct font_path_info *info, struct dstr *cmp)
{
const char *src = info->face_and_style;
const char *dst = cmp->array;
size_t num = 0;
do {
char ch1 = (char)toupper(*src);
char ch2 = (char)toupper(*dst);
if (ch1 != ch2)
break;
num++;
} while (*src++ && *dst++);
return num;
}
const char *get_font_path(const char *family, uint16_t size, const char *style,
uint32_t flags, FT_Long *idx)
{
const char *best_path = NULL;
double best_rating = 0.0;
struct dstr face_and_style = {0};
struct dstr style_str = {0};
bool bold = !!(flags & OBS_FONT_BOLD);
bool italic = !!(flags & OBS_FONT_ITALIC);
if (!family || !*family)
return NULL;
if (style) {
dstr_copy(&style_str, style);
dstr_replace(&style_str, "Bold", "");
dstr_replace(&style_str, "Italic", "");
dstr_replace(&style_str, " ", " ");
dstr_depad(&style_str);
}
dstr_copy(&face_and_style, family);
if (!dstr_is_empty(&style_str)) {
dstr_cat(&face_and_style, " ");
dstr_cat_dstr(&face_and_style, &style_str);
}
for (size_t i = 0; i < font_list.num; i++) {
struct font_path_info *info = font_list.array + i;
double rating = (double)get_rating(info, &face_and_style);
if (rating < info->face_len)
continue;
if (info->is_bitmap) {
int best_diff = 1000;
for (uint32_t j = 0; j < info->num_sizes; j++) {
int diff = abs(info->sizes[j] - size);
if (diff < best_diff)
best_diff = diff;
}
rating /= (double)(best_diff + 1.0);
}
if (info->bold == bold) rating += 1.0;
if (info->italic == italic) rating += 1.0;
if (rating > best_rating) {
best_path = info->path;
*idx = info->index;
best_rating = rating;
}
}
dstr_free(&style_str);
dstr_free(&face_and_style);
return best_path;
}

View file

@ -0,0 +1,41 @@
#pragma once
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_SFNT_NAMES_H
#include FT_TRUETYPE_IDS_H
#include <util/dstr.h>
#include <util/darray.h>
struct font_path_info {
char *face_and_style;
uint32_t full_len;
uint32_t face_len;
bool is_bitmap;
uint32_t num_sizes;
int *sizes;
bool bold;
bool italic;
char *path;
FT_Long index;
};
static inline void font_path_info_free(struct font_path_info *info)
{
bfree(info->sizes);
bfree(info->face_and_style);
bfree(info->path);
}
extern void build_font_path_info(FT_Face face, FT_Long idx, const char *path);
extern char *sfnt_name_to_utf8(FT_SfntName *sfnt_name);
extern bool load_cached_os_font_list(void);
extern void load_os_font_list(void);
extern void free_os_font_list(void);
extern const char *get_font_path(const char *family, uint16_t size,
const char *style, uint32_t flags, FT_Long *idx);

View file

@ -0,0 +1,85 @@
/******************************************************************************
Copyright (C) 2014 by Nibbles
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <obs-module.h>
#include <graphics/vec2.h>
#include <graphics/vec3.h>
#include <graphics/vec4.h>
#include "obs-convenience.h"
gs_vertbuffer_t *create_uv_vbuffer(uint32_t num_verts, bool add_color) {
obs_enter_graphics();
gs_vertbuffer_t *tmp = NULL;
struct gs_vb_data *vrect = NULL;
vrect = gs_vbdata_create();
vrect->num = num_verts;
vrect->points = (struct vec3 *)bmalloc(sizeof(struct vec3) * num_verts);
vrect->num_tex = 1;
vrect->tvarray =
(struct gs_tvertarray *)bmalloc(sizeof(struct gs_tvertarray));
vrect->tvarray[0].width = 2;
vrect->tvarray[0].array = bmalloc(sizeof(struct vec2) * num_verts);
if (add_color)
vrect->colors = (uint32_t *)bmalloc
(sizeof(uint32_t)* num_verts);
memset(vrect->points, 0, sizeof(struct vec3) * num_verts);
memset(vrect->tvarray[0].array, 0, sizeof(struct vec2) * num_verts);
if (add_color)
memset(vrect->colors, 0, sizeof(uint32_t)* num_verts);
tmp = gs_vertexbuffer_create(vrect, GS_DYNAMIC);
if (tmp == NULL) {
blog(LOG_WARNING, "Couldn't create UV vertex buffer.");
}
obs_leave_graphics();
return tmp;
}
void draw_uv_vbuffer(gs_vertbuffer_t *vbuf, gs_texture_t *tex,
gs_effect_t *effect, uint32_t num_verts)
{
gs_texture_t *texture = tex;
gs_technique_t *tech = gs_effect_get_technique(effect, "Draw");
gs_eparam_t *image = gs_effect_get_param_by_name(effect, "image");
size_t passes;
if (vbuf == NULL || tex == NULL) return;
gs_vertexbuffer_flush(vbuf);
gs_load_vertexbuffer(vbuf);
gs_load_indexbuffer(NULL);
passes = gs_technique_begin(tech);
for (size_t i = 0; i < passes; i++) {
if (gs_technique_begin_pass(tech, i)) {
gs_effect_set_texture(image, texture);
gs_draw(GS_TRIS, 0, num_verts);
gs_technique_end_pass(tech);
}
}
gs_technique_end(tech);
}

View file

@ -0,0 +1,43 @@
/******************************************************************************
Copyright (C) 2014 by Nibbles
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <obs-module.h>
gs_vertbuffer_t *create_uv_vbuffer(uint32_t num_verts, bool add_color);
void draw_uv_vbuffer(gs_vertbuffer_t *vbuf, gs_texture_t *tex,
gs_effect_t *effect, uint32_t num_verts);
#define set_v3_rect(a, x, y, w, h) \
vec3_set(a, x, y, 0.0f); \
vec3_set(a + 1, x + w, y, 0.0f); \
vec3_set(a + 2, x, y + h, 0.0f); \
vec3_set(a + 3, x, y + h, 0.0f); \
vec3_set(a + 4, x + w, y, 0.0f); \
vec3_set(a + 5, x + w, y + h, 0.0f);
#define set_v2_uv(a, u, v, u2, v2) \
vec2_set(a, u, v); \
vec2_set(a + 1, u2, v); \
vec2_set(a + 2, u, v2); \
vec2_set(a + 3, u, v2); \
vec2_set(a + 4, u2, v); \
vec2_set(a + 5, u2, v2);
#define set_rect_colors2(a, c1, c2) \
uint32_t *b = a; \
b[0] = b[1] = b[4] = c1; \
b[2] = b[3] = b[5] = c2;

View file

@ -0,0 +1,456 @@
/******************************************************************************
Copyright (C) 2014 by Nibbles
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <obs-module.h>
#include <util/platform.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <sys/stat.h>
#include "text-freetype2.h"
#include "obs-convenience.h"
#include "find-font.h"
FT_Library ft2_lib;
OBS_DECLARE_MODULE()
OBS_MODULE_USE_DEFAULT_LOCALE("text-freetype2", "en-US")
uint32_t texbuf_w = 2048, texbuf_h = 2048;
static struct obs_source_info freetype2_source_info = {
.id = "text_ft2_source",
.type = OBS_SOURCE_TYPE_INPUT,
.output_flags = OBS_SOURCE_VIDEO,
.get_name = ft2_source_get_name,
.create = ft2_source_create,
.destroy = ft2_source_destroy,
.update = ft2_source_update,
.get_width = ft2_source_get_width,
.get_height = ft2_source_get_height,
.video_render = ft2_source_render,
.video_tick = ft2_video_tick,
.get_properties = ft2_source_properties,
};
bool obs_module_load()
{
char *config_dir = obs_module_config_path(NULL);
if (config_dir) {
os_mkdirs(config_dir);
bfree(config_dir);
}
FT_Init_FreeType(&ft2_lib);
if (ft2_lib == NULL) {
blog(LOG_WARNING, "FT2-text: Failed to initialize FT2.");
return false;
}
if (!load_cached_os_font_list())
load_os_font_list();
obs_register_source(&freetype2_source_info);
return true;
}
void obs_module_unload(void)
{
free_os_font_list();
FT_Done_FreeType(ft2_lib);
}
static const char *ft2_source_get_name(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("TextFreetype2");
}
static uint32_t ft2_source_get_width(void *data)
{
struct ft2_source *srcdata = data;
return srcdata->cx;
}
static uint32_t ft2_source_get_height(void *data)
{
struct ft2_source *srcdata = data;
return srcdata->cy;
}
static obs_properties_t *ft2_source_properties(void *unused)
{
UNUSED_PARAMETER(unused);
obs_properties_t *props = obs_properties_create();
//obs_property_t *prop;
// TODO:
// Scrolling. Can't think of a way to do it with the render
// targets currently being broken. (0.4.2)
// Better/pixel shader outline/drop shadow
// Some way to pull text files from network, I dunno
obs_properties_add_font(props, "font",
obs_module_text("Font"));
obs_properties_add_text(props, "text",
obs_module_text("Text"), OBS_TEXT_MULTILINE);
obs_properties_add_bool(props, "from_file",
obs_module_text("ReadFromFile"));
obs_properties_add_bool(props, "log_mode",
obs_module_text("ChatLogMode"));
obs_properties_add_path(props,
"text_file", obs_module_text("TextFile"),
OBS_PATH_FILE, obs_module_text("TextFileFilter"), NULL);
obs_properties_add_color(props, "color1",
obs_module_text("Color1"));
obs_properties_add_color(props, "color2",
obs_module_text("Color2"));
obs_properties_add_bool(props, "outline",
obs_module_text("Outline"));
obs_properties_add_bool(props, "drop_shadow",
obs_module_text("DropShadow"));
obs_properties_add_int(props, "custom_width",
obs_module_text("CustomWidth"), 0, 4096, 1);
obs_properties_add_bool(props, "word_wrap",
obs_module_text("WordWrap"));
return props;
}
static void ft2_source_destroy(void *data)
{
struct ft2_source *srcdata = data;
if (srcdata->font_face != NULL) {
FT_Done_Face(srcdata->font_face);
srcdata->font_face = NULL;
}
for (uint32_t i = 0; i < num_cache_slots; i++) {
if (srcdata->cacheglyphs[i] != NULL) {
bfree(srcdata->cacheglyphs[i]);
srcdata->cacheglyphs[i] = NULL;
}
}
if (srcdata->font_name != NULL)
bfree(srcdata->font_name);
if (srcdata->font_style != NULL)
bfree(srcdata->font_style);
if (srcdata->text != NULL)
bfree(srcdata->text);
if (srcdata->texbuf != NULL)
bfree(srcdata->texbuf);
if (srcdata->colorbuf != NULL)
bfree(srcdata->colorbuf);
if (srcdata->text_file != NULL)
bfree(srcdata->text_file);
obs_enter_graphics();
if (srcdata->tex != NULL) {
gs_texture_destroy(srcdata->tex);
srcdata->tex = NULL;
}
if (srcdata->vbuf != NULL) {
gs_vertexbuffer_destroy(srcdata->vbuf);
srcdata->vbuf = NULL;
}
if (srcdata->draw_effect != NULL) {
gs_effect_destroy(srcdata->draw_effect);
srcdata->draw_effect = NULL;
}
obs_leave_graphics();
bfree(srcdata);
}
static void ft2_source_render(void *data, gs_effect_t *effect)
{
struct ft2_source *srcdata = data;
if (srcdata == NULL) return;
if (srcdata->tex == NULL || srcdata->vbuf == NULL) return;
gs_reset_blend_state();
if (srcdata->outline_text) draw_outlines(srcdata);
if (srcdata->drop_shadow) draw_drop_shadow(srcdata);
draw_uv_vbuffer(srcdata->vbuf, srcdata->tex,
srcdata->draw_effect, (uint32_t)wcslen(srcdata->text) * 6);
UNUSED_PARAMETER(effect);
}
static void ft2_video_tick(void *data, float seconds)
{
struct ft2_source *srcdata = data;
if (srcdata == NULL) return;
if (!srcdata->from_file || !srcdata->text_file) return;
if (os_gettime_ns() - srcdata->last_checked >= 1000000000) {
time_t t = get_modified_timestamp(srcdata->text_file);
srcdata->last_checked = os_gettime_ns();
if (srcdata->m_timestamp != t) {
if (srcdata->log_mode)
read_from_end(srcdata, srcdata->text_file);
else
load_text_from_file(srcdata,
srcdata->text_file);
cache_glyphs(srcdata, srcdata->text);
set_up_vertex_buffer(srcdata);
}
}
UNUSED_PARAMETER(seconds);
}
static bool init_font(struct ft2_source *srcdata)
{
FT_Long index;
const char *path = get_font_path(srcdata->font_name, srcdata->font_size,
srcdata->font_style, srcdata->font_flags, &index);
if (!path)
return false;
if (srcdata->font_face != NULL) {
FT_Done_Face(srcdata->font_face);
srcdata->font_face = NULL;
}
return FT_New_Face(ft2_lib, path, index, &srcdata->font_face) == 0;
}
static void ft2_source_update(void *data, obs_data_t *settings)
{
struct ft2_source *srcdata = data;
obs_data_t *font_obj = obs_data_get_obj(settings, "font");
bool vbuf_needs_update = false;
bool word_wrap = false;
uint32_t color[2];
uint32_t custom_width = 0;
const char *font_name = obs_data_get_string(font_obj, "face");
const char *font_style = obs_data_get_string(font_obj, "style");
uint16_t font_size = (uint16_t)obs_data_get_int(font_obj, "size");
uint32_t font_flags = (uint32_t)obs_data_get_int(font_obj, "flags");
if (!font_obj)
return;
srcdata->drop_shadow = obs_data_get_bool(settings, "drop_shadow");
srcdata->outline_text = obs_data_get_bool(settings, "outline");
word_wrap = obs_data_get_bool(settings, "word_wrap");
color[0] = (uint32_t)obs_data_get_int(settings, "color1");
color[1] = (uint32_t)obs_data_get_int(settings, "color2");
custom_width = (uint32_t)obs_data_get_int(settings, "custom_width");
if (custom_width >= 100) {
if (custom_width != srcdata->custom_width) {
srcdata->custom_width = custom_width;
vbuf_needs_update = true;
}
}
else {
if (srcdata->custom_width >= 100)
vbuf_needs_update = true;
srcdata->custom_width = 0;
}
if (word_wrap != srcdata->word_wrap) {
srcdata->word_wrap = word_wrap;
vbuf_needs_update = true;
}
if (color[0] != srcdata->color[0] || color[1] != srcdata->color[1]) {
srcdata->color[0] = color[0];
srcdata->color[1] = color[1];
vbuf_needs_update = true;
}
bool from_file = obs_data_get_bool(settings, "from_file");
bool chat_log_mode = obs_data_get_bool(settings, "log_mode");
srcdata->log_mode = chat_log_mode;
if (ft2_lib == NULL) goto error;
if (srcdata->draw_effect == NULL) {
char *effect_file = NULL;
char *error_string = NULL;
effect_file =
obs_module_file("text_default.effect");
if (effect_file) {
obs_enter_graphics();
srcdata->draw_effect = gs_effect_create_from_file(
effect_file, &error_string);
obs_leave_graphics();
bfree(effect_file);
if (error_string != NULL)
bfree(error_string);
}
}
if (srcdata->font_size != font_size ||
srcdata->from_file != from_file)
vbuf_needs_update = true;
srcdata->file_load_failed = false;
srcdata->from_file = from_file;
if (srcdata->font_name != NULL) {
if (strcmp(font_name, srcdata->font_name) == 0 &&
strcmp(font_style, srcdata->font_style) == 0 &&
font_flags == srcdata->font_flags &&
font_size == srcdata->font_size)
goto skip_font_load;
bfree(srcdata->font_name);
bfree(srcdata->font_style);
srcdata->font_name = NULL;
srcdata->font_style = NULL;
srcdata->max_h = 0;
vbuf_needs_update = true;
}
srcdata->font_name = bstrdup(font_name);
srcdata->font_style = bstrdup(font_style);
srcdata->font_size = font_size;
srcdata->font_flags = font_flags;
if (!init_font(srcdata) || srcdata->font_face == NULL) {
blog(LOG_WARNING, "FT2-text: Failed to load font %s",
srcdata->font_name);
goto error;
}
else {
FT_Set_Pixel_Sizes(srcdata->font_face, 0, srcdata->font_size);
FT_Select_Charmap(srcdata->font_face, FT_ENCODING_UNICODE);
}
if (srcdata->texbuf != NULL) {
bfree(srcdata->texbuf);
srcdata->texbuf = NULL;
}
srcdata->texbuf = bzalloc(texbuf_w * texbuf_h * 4);
if (srcdata->font_face)
cache_standard_glyphs(srcdata);
skip_font_load:
if (from_file) {
const char *tmp = obs_data_get_string(settings, "text_file");
if (!tmp || !*tmp || !os_file_exists(tmp)) {
const char *emptystr = " ";
bfree(srcdata->text);
srcdata->text = NULL;
os_utf8_to_wcs_ptr(emptystr, strlen(emptystr),
&srcdata->text);
blog(LOG_WARNING, "FT2-text: Failed to open %s for "
"reading", tmp);
}
else {
if (srcdata->text_file != NULL &&
strcmp(srcdata->text_file, tmp) == 0 &&
!vbuf_needs_update)
goto error;
bfree(srcdata->text_file);
srcdata->text_file = bstrdup(tmp);
if (chat_log_mode)
read_from_end(srcdata, tmp);
else
load_text_from_file(srcdata, tmp);
srcdata->last_checked = os_gettime_ns();
}
}
else {
const char *tmp = obs_data_get_string(settings, "text");
if (!tmp || !*tmp) goto error;
if (srcdata->text != NULL) {
bfree(srcdata->text);
srcdata->text = NULL;
}
os_utf8_to_wcs_ptr(tmp, strlen(tmp), &srcdata->text);
}
if (srcdata->font_face) {
cache_glyphs(srcdata, srcdata->text);
set_up_vertex_buffer(srcdata);
}
error:
obs_data_release(font_obj);
}
#ifdef _WIN32
#define DEFAULT_FACE "Arial"
#elif __APPLE__
#define DEFAULT_FACE "Helvetica"
#else
#define DEFAULT_FACE "Sans Serif"
#endif
static void *ft2_source_create(obs_data_t *settings, obs_source_t *source)
{
struct ft2_source *srcdata = bzalloc(sizeof(struct ft2_source));
obs_data_t *font_obj = obs_data_create();
srcdata->src = source;
srcdata->font_size = 32;
obs_data_set_default_string(font_obj, "face", DEFAULT_FACE);
obs_data_set_default_int(font_obj, "size", 32);
obs_data_set_default_obj(settings, "font", font_obj);
obs_data_set_default_int(settings, "color1", 0xFFFFFFFF);
obs_data_set_default_int(settings, "color2", 0xFFFFFFFF);
obs_data_set_default_string(settings, "text",
"The lazy snake jumps over the happy MASKEN.");
ft2_source_update(srcdata, settings);
obs_data_release(font_obj);
return srcdata;
}

View file

@ -0,0 +1,94 @@
/******************************************************************************
Copyright (C) 2014 by Nibbles
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <obs-module.h>
#include <ft2build.h>
#define num_cache_slots 65535
#define src_glyph srcdata->cacheglyphs[glyph_index]
struct glyph_info {
float u, v, u2, v2;
int32_t w, h, xoff, yoff;
int32_t xadv;
};
struct ft2_source {
char *font_name;
char *font_style;
uint16_t font_size;
uint32_t font_flags;
bool file_load_failed;
bool from_file;
char *text_file;
wchar_t *text;
time_t m_timestamp;
uint64_t last_checked;
uint32_t cx, cy, max_h, custom_width;
uint32_t texbuf_x, texbuf_y;
uint32_t color[2];
uint32_t *colorbuf;
int32_t cur_scroll, scroll_speed;
gs_texture_t *tex;
struct glyph_info *cacheglyphs[num_cache_slots];
FT_Face font_face;
uint32_t *texbuf;
gs_vertbuffer_t *vbuf;
gs_effect_t *draw_effect;
bool outline_text, drop_shadow;
bool log_mode, word_wrap;
obs_source_t *src;
};
extern FT_Library ft2_lib;
static void *ft2_source_create(obs_data_t *settings, obs_source_t *source);
static void ft2_source_destroy(void *data);
static void ft2_source_update(void *data, obs_data_t *settings);
static void ft2_source_render(void *data, gs_effect_t *effect);
static void ft2_video_tick(void *data, float seconds);
void draw_outlines(struct ft2_source *srcdata);
void draw_drop_shadow(struct ft2_source *srcdata);
static uint32_t ft2_source_get_width(void *data);
static uint32_t ft2_source_get_height(void *data);
static obs_properties_t *ft2_source_properties(void *unused);
static const char *ft2_source_get_name(void *unused);
uint32_t get_ft2_text_width(wchar_t *text, struct ft2_source *srcdata);
time_t get_modified_timestamp(char *filename);
void load_text_from_file(struct ft2_source *srcdata, const char *filename);
void read_from_end(struct ft2_source *srcdata, const char *filename);
void cache_standard_glyphs(struct ft2_source *srcdata);
void cache_glyphs(struct ft2_source *srcdata, wchar_t *cache_glyphs);
void set_up_vertex_buffer(struct ft2_source *srcdata);
void fill_vertex_buffer(struct ft2_source *srcdata);

View file

@ -0,0 +1,506 @@
/******************************************************************************
Copyright (C) 2014 by Nibbles
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <obs-module.h>
#include <util/platform.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <sys/stat.h>
#include "text-freetype2.h"
#include "obs-convenience.h"
float offsets[16] = { -2.0f, 0.0f, 0.0f, -2.0f, 2.0f, 0.0f, 2.0f, 0.0f,
0.0f, 2.0f, 0.0f, 2.0f, -2.0f, 0.0f, -2.0f, 0.0f };
extern uint32_t texbuf_w, texbuf_h;
void draw_outlines(struct ft2_source *srcdata)
{
// Horrible (hopefully temporary) solution for outlines.
uint32_t *tmp;
struct gs_vb_data *vdata = gs_vertexbuffer_get_data(srcdata->vbuf);
if (!srcdata->text)
return;
tmp = vdata->colors;
vdata->colors = srcdata->colorbuf;
gs_matrix_push();
for (int32_t i = 0; i < 8; i++) {
gs_matrix_translate3f(offsets[i * 2], offsets[(i * 2) + 1],
0.0f);
draw_uv_vbuffer(srcdata->vbuf, srcdata->tex,
srcdata->draw_effect,
(uint32_t)wcslen(srcdata->text) * 6);
}
gs_matrix_identity();
gs_matrix_pop();
vdata->colors = tmp;
}
void draw_drop_shadow(struct ft2_source *srcdata)
{
// Horrible (hopefully temporary) solution for drop shadow.
uint32_t *tmp;
struct gs_vb_data *vdata = gs_vertexbuffer_get_data(srcdata->vbuf);
if (!srcdata->text)
return;
tmp = vdata->colors;
vdata->colors = srcdata->colorbuf;
gs_matrix_push();
gs_matrix_translate3f(4.0f, 4.0f, 0.0f);
draw_uv_vbuffer(srcdata->vbuf, srcdata->tex,
srcdata->draw_effect, (uint32_t)wcslen(srcdata->text) * 6);
gs_matrix_identity();
gs_matrix_pop();
vdata->colors = tmp;
}
void set_up_vertex_buffer(struct ft2_source *srcdata)
{
FT_UInt glyph_index = 0;
uint32_t x = 0, space_pos = 0, word_width = 0;
size_t len;
if (!srcdata->text)
return;
if (srcdata->custom_width >= 100)
srcdata->cx = srcdata->custom_width;
else
srcdata->cx = get_ft2_text_width(srcdata->text, srcdata);
srcdata->cy = srcdata->max_h;
obs_enter_graphics();
if (srcdata->vbuf != NULL) {
gs_vertbuffer_t *tmpvbuf = srcdata->vbuf;
srcdata->vbuf = NULL;
gs_vertexbuffer_destroy(tmpvbuf);
}
srcdata->vbuf = create_uv_vbuffer((uint32_t)wcslen(srcdata->text) * 6,
true);
if (srcdata->custom_width <= 100) goto skip_word_wrap;
if (!srcdata->word_wrap) goto skip_word_wrap;
len = wcslen(srcdata->text);
for (uint32_t i = 0; i <= len; i++) {
if (i == wcslen(srcdata->text)) goto eos_check;
if (srcdata->text[i] != L' ' && srcdata->text[i] != L'\n')
goto next_char;
eos_check:;
if (x + word_width > srcdata->custom_width) {
if (space_pos != 0)
srcdata->text[space_pos] = L'\n';
x = 0;
}
if (i == wcslen(srcdata->text)) goto eos_skip;
x += word_width;
word_width = 0;
if (srcdata->text[i] == L'\n')
x = 0;
if (srcdata->text[i] == L' ')
space_pos = i;
next_char:;
glyph_index = FT_Get_Char_Index(srcdata->font_face,
srcdata->text[i]);
word_width += src_glyph->xadv;
eos_skip:;
}
skip_word_wrap:;
fill_vertex_buffer(srcdata);
obs_leave_graphics();
}
void fill_vertex_buffer(struct ft2_source *srcdata)
{
struct gs_vb_data *vdata = gs_vertexbuffer_get_data(srcdata->vbuf);
if (vdata == NULL || !srcdata->text) return;
struct vec2 *tvarray = (struct vec2 *)vdata->tvarray[0].array;
uint32_t *col = (uint32_t *)vdata->colors;
FT_UInt glyph_index = 0;
uint32_t dx = 0, dy = srcdata->max_h, max_y = dy;
uint32_t cur_glyph = 0;
size_t len = wcslen(srcdata->text);
if (srcdata->colorbuf != NULL) {
bfree(srcdata->colorbuf);
srcdata->colorbuf = NULL;
}
srcdata->colorbuf = bzalloc(sizeof(uint32_t)*wcslen(srcdata->text) * 6);
for (size_t i = 0; i < len * 6; i++) {
srcdata->colorbuf[i] = 0xFF000000;
}
for (size_t i = 0; i < len; i++) {
add_linebreak:;
if (srcdata->text[i] != L'\n') goto draw_glyph;
dx = 0; i++;
dy += srcdata->max_h + 4;
if (i == wcslen(srcdata->text)) goto skip_glyph;
if (srcdata->text[i] == L'\n') goto add_linebreak;
draw_glyph:;
// Skip filthy dual byte Windows line breaks
if (srcdata->text[i] == L'\r') goto skip_glyph;
glyph_index = FT_Get_Char_Index(srcdata->font_face,
srcdata->text[i]);
if (src_glyph == NULL)
goto skip_glyph;
if (srcdata->custom_width < 100) goto skip_custom_width;
if (dx + src_glyph->xadv > srcdata->custom_width) {
dx = 0;
dy += srcdata->max_h + 4;
}
skip_custom_width:;
set_v3_rect(vdata->points + (cur_glyph * 6),
(float)dx + (float)src_glyph->xoff,
(float)dy - (float)src_glyph->yoff,
(float)src_glyph->w,
(float)src_glyph->h);
set_v2_uv(tvarray + (cur_glyph * 6),
src_glyph->u,
src_glyph->v,
src_glyph->u2,
src_glyph->v2);
set_rect_colors2(col + (cur_glyph * 6),
srcdata->color[0],
srcdata->color[1]);
dx += src_glyph->xadv;
if (dy - (float)src_glyph->yoff + src_glyph->h > max_y)
max_y = dy - src_glyph->yoff + src_glyph->h;
cur_glyph++;
skip_glyph:;
}
srcdata->cy = max_y;
}
void cache_standard_glyphs(struct ft2_source *srcdata)
{
for (uint32_t i = 0; i < num_cache_slots; i++) {
if (srcdata->cacheglyphs[i] != NULL) {
bfree(srcdata->cacheglyphs[i]);
srcdata->cacheglyphs[i] = NULL;
}
}
srcdata->texbuf_x = 0;
srcdata->texbuf_y = 0;
cache_glyphs(srcdata, L"abcdefghijklmnopqrstuvwxyz" \
L"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" \
L"!@#$%^&*()-_=+,<.>/?\\|[]{}`~ \'\"\0");
}
#define glyph_pos x + (y*slot->bitmap.pitch)
#define buf_pos (dx + x) + ((dy + y) * texbuf_w)
void cache_glyphs(struct ft2_source *srcdata, wchar_t *cache_glyphs)
{
FT_GlyphSlot slot;
FT_UInt glyph_index = 0;
if (!srcdata->font_face || !cache_glyphs)
return;
slot = srcdata->font_face->glyph;
uint32_t dx = srcdata->texbuf_x, dy = srcdata->texbuf_y;
uint8_t alpha;
int32_t cached_glyphs = 0;
size_t len = wcslen(cache_glyphs);
for (size_t i = 0; i < len; i++) {
glyph_index = FT_Get_Char_Index(srcdata->font_face,
cache_glyphs[i]);
if (src_glyph != NULL)
goto skip_glyph;
FT_Load_Glyph(srcdata->font_face, glyph_index, FT_LOAD_DEFAULT);
FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
uint32_t g_w = slot->bitmap.width;
uint32_t g_h = slot->bitmap.rows;
if (srcdata->max_h < g_h) srcdata->max_h = g_h;
if (dx + g_w >= texbuf_w) {
dx = 0;
dy += srcdata->max_h + 1;
}
src_glyph = bzalloc(sizeof(struct glyph_info));
src_glyph->u = (float)dx / (float)texbuf_w;
src_glyph->u2 = (float)(dx + g_w) / (float)texbuf_w;
src_glyph->v = (float)dy / (float)texbuf_h;
src_glyph->v2 = (float)(dy + g_h) / (float)texbuf_h;
src_glyph->w = g_w;
src_glyph->h = g_h;
src_glyph->yoff = slot->bitmap_top;
src_glyph->xoff = slot->bitmap_left;
src_glyph->xadv = slot->advance.x >> 6;
for (uint32_t y = 0; y < g_h; y++) {
for (uint32_t x = 0; x < g_w; x++) {
alpha = slot->bitmap.buffer[glyph_pos];
srcdata->texbuf[buf_pos] =
0x00FFFFFF ^ ((uint32_t)alpha << 24);
}
}
dx += (g_w + 1);
if (dx >= texbuf_w) {
dx = 0;
dy += srcdata->max_h;
}
cached_glyphs++;
skip_glyph:;
}
srcdata->texbuf_x = dx;
srcdata->texbuf_y = dy;
if (cached_glyphs > 0) {
obs_enter_graphics();
if (srcdata->tex != NULL) {
gs_texture_t *tmp_texture = NULL;
tmp_texture = srcdata->tex;
srcdata->tex = NULL;
gs_texture_destroy(tmp_texture);
}
srcdata->tex = gs_texture_create(texbuf_w, texbuf_h,
GS_RGBA, 1, (const uint8_t **)&srcdata->texbuf, 0);
obs_leave_graphics();
}
}
time_t get_modified_timestamp(char *filename)
{
struct stat stats;
// stat is apparently terrifying and horrible, but we only call it once
// every second at most.
stat(filename, &stats);
return stats.st_mtime;
}
static void remove_cr(wchar_t* source)
{
int j = 0;
for (int i = 0; source[i] != '\0'; ++i) {
if (source[i] != L'\r') {
source[j++] = source[i];
}
}
source[j] = '\0';
}
void load_text_from_file(struct ft2_source *srcdata, const char *filename)
{
FILE *tmp_file = NULL;
uint32_t filesize = 0;
char *tmp_read = NULL;
uint16_t header = 0;
size_t bytes_read;
tmp_file = os_fopen(filename, "rb");
if (tmp_file == NULL) {
if (!srcdata->file_load_failed) {
blog(LOG_WARNING, "Failed to open file %s", filename);
srcdata->file_load_failed = true;
}
return;
}
fseek(tmp_file, 0, SEEK_END);
filesize = (uint32_t)ftell(tmp_file);
fseek(tmp_file, 0, SEEK_SET);
bytes_read = fread(&header, 2, 1, tmp_file);
if (bytes_read == 2 && header == 0xFEFF) {
// File is already in UTF-16 format
if (srcdata->text != NULL) {
bfree(srcdata->text);
srcdata->text = NULL;
}
srcdata->text = bzalloc(filesize);
bytes_read = fread(srcdata->text, filesize - 2, 1, tmp_file);
srcdata->m_timestamp =
get_modified_timestamp(srcdata->text_file);
bfree(tmp_read);
fclose(tmp_file);
return;
}
fseek(tmp_file, 0, SEEK_SET);
srcdata->m_timestamp = get_modified_timestamp(srcdata->text_file);
tmp_read = bzalloc(filesize + 1);
bytes_read = fread(tmp_read, filesize, 1, tmp_file);
fclose(tmp_file);
if (srcdata->text != NULL) {
bfree(srcdata->text);
srcdata->text = NULL;
}
srcdata->text = bzalloc((strlen(tmp_read) + 1)*sizeof(wchar_t));
os_utf8_to_wcs(tmp_read, strlen(tmp_read),
srcdata->text, (strlen(tmp_read) + 1));
remove_cr(srcdata->text);
bfree(tmp_read);
}
void read_from_end(struct ft2_source *srcdata, const char *filename)
{
FILE *tmp_file = NULL;
uint32_t filesize = 0, cur_pos = 0;
char *tmp_read = NULL;
uint16_t value = 0, line_breaks = 0;
size_t bytes_read;
char bvalue;
bool utf16 = false;
tmp_file = fopen(filename, "rb");
if (tmp_file == NULL) {
if (!srcdata->file_load_failed) {
blog(LOG_WARNING, "Failed to open file %s", filename);
srcdata->file_load_failed = true;
}
return;
}
bytes_read = fread(&value, 2, 1, tmp_file);
if (bytes_read == 2 && value == 0xFEFF)
utf16 = true;
fseek(tmp_file, 0, SEEK_END);
filesize = (uint32_t)ftell(tmp_file);
cur_pos = filesize;
while (line_breaks <= 6 && cur_pos != 0) {
if (!utf16) cur_pos--;
else cur_pos -= 2;
fseek(tmp_file, cur_pos, SEEK_SET);
if (!utf16) {
bytes_read = fread(&bvalue, 1, 1, tmp_file);
if (bytes_read == 1 && bvalue == '\n')
line_breaks++;
}
else {
bytes_read = fread(&value, 2, 1, tmp_file);
if (bytes_read == 2 && value == L'\n')
line_breaks++;
}
}
if (cur_pos != 0)
cur_pos += (utf16) ? 2 : 1;
fseek(tmp_file, cur_pos, SEEK_SET);
if (utf16) {
if (srcdata->text != NULL) {
bfree(srcdata->text);
srcdata->text = NULL;
}
srcdata->text = bzalloc(filesize - cur_pos);
bytes_read = fread(srcdata->text, (filesize - cur_pos), 1,
tmp_file);
remove_cr(srcdata->text);
srcdata->m_timestamp =
get_modified_timestamp(srcdata->text_file);
bfree(tmp_read);
fclose(tmp_file);
return;
}
tmp_read = bzalloc((filesize - cur_pos) + 1);
bytes_read = fread(tmp_read, filesize - cur_pos, 1, tmp_file);
fclose(tmp_file);
if (srcdata->text != NULL) {
bfree(srcdata->text);
srcdata->text = NULL;
}
srcdata->text = bzalloc((strlen(tmp_read) + 1)*sizeof(wchar_t));
os_utf8_to_wcs(tmp_read, strlen(tmp_read),
srcdata->text, (strlen(tmp_read) + 1));
remove_cr(srcdata->text);
srcdata->m_timestamp = get_modified_timestamp(srcdata->text_file);
bfree(tmp_read);
}
uint32_t get_ft2_text_width(wchar_t *text, struct ft2_source *srcdata)
{
FT_GlyphSlot slot = srcdata->font_face->glyph;
FT_UInt glyph_index = 0;
uint32_t w = 0, max_w = 0;
size_t len;
if (!text)
return 0;
len = wcslen(text);
for (size_t i = 0; i < len; i++) {
glyph_index = FT_Get_Char_Index(srcdata->font_face, text[i]);
FT_Load_Glyph(srcdata->font_face, glyph_index, FT_LOAD_DEFAULT);
if (text[i] == L'\n') w = 0;
else {
w += slot->advance.x >> 6;
if (w > max_w) max_w = w;
}
}
return max_w;
}