[MPlayer-cvslog] r18942 - in trunk: DOCS/man/en/mplayer.1 Makefile cfg-common.h configure libass libass/Makefile libass/ass.c libass/ass.h libass/ass_cache.c libass/ass_cache.h libass/ass_fontconfig.c libass/ass_fontconfig.h libass/ass_mp.c libass/ass_mp.h libass/ass_render.c libass/ass_types.h libass/ass_utils.c libass/ass_utils.h libmpcodecs/Makefile libmpcodecs/vf.c libmpcodecs/vf.h libmpcodecs/vf_ass.c libmpcodecs/vfcap.h libmpdemux/demux_mkv.c libmpdemux/demuxer.h libmpdemux/ebml.h mencoder.c mplayer.c

eugeni subversion at mplayerhq.hu
Fri Jul 7 20:26:52 CEST 2006


Author: eugeni
Date: Fri Jul  7 20:26:51 2006
New Revision: 18942

Added:
   trunk/libass/
   trunk/libass/Makefile
   trunk/libass/ass.c
   trunk/libass/ass.h
   trunk/libass/ass_cache.c
   trunk/libass/ass_cache.h
   trunk/libass/ass_fontconfig.c
   trunk/libass/ass_fontconfig.h
   trunk/libass/ass_mp.c
   trunk/libass/ass_mp.h
   trunk/libass/ass_render.c
   trunk/libass/ass_types.h
   trunk/libass/ass_utils.c
   trunk/libass/ass_utils.h
   trunk/libmpcodecs/vf_ass.c
Modified:
   trunk/Makefile
   trunk/cfg-common.h
   trunk/configure
   trunk/libmpcodecs/Makefile
   trunk/libmpcodecs/vf.c
   trunk/libmpcodecs/vf.h
   trunk/libmpcodecs/vfcap.h
   trunk/libmpdemux/demux_mkv.c
   trunk/libmpdemux/demuxer.h
   trunk/libmpdemux/ebml.h
   trunk/mencoder.c
   trunk/mplayer.c

Changes in other areas also in this revision:
Modified:
   trunk/DOCS/man/en/mplayer.1

Log:
Initial libass release (without mencoder support).


Modified: trunk/Makefile
==============================================================================
--- trunk/Makefile	(original)
+++ trunk/Makefile	Fri Jul  7 20:26:51 2006
@@ -82,6 +82,12 @@
 VO_LIBS += $(EXTERNAL_VIDIX_LIB)
 endif
 
+ASS_LIB =
+
+ifeq ($(CONFIG_ASS),yes)
+ASS_LIB += libass/libass.a
+endif
+
 AO_LIBS = $(ARTS_LIB) \
           $(ESD_LIB) \
           $(JACK_LIB) \
@@ -113,6 +119,7 @@
               $(W32_LIB) \
               libaf/libaf.a \
               libmpdemux/libmpdemux.a \
+              $(ASS_LIB) \
               libswscale/libswscale.a \
               osdep/libosdep.a \
               $(DVDREAD_LIB) \
@@ -254,6 +261,10 @@
 ifeq ($(DVDKIT2),yes)
 COMMON_DEPS += libmpdvdkit2/libmpdvdkit.a
 endif
+ifeq ($(CONFIG_ASS),yes)
+COMMON_DEPS += libass/libass.a
+PARTS += libass
+endif
 
 ifeq ($(GUI),yes)
 COMMON_DEPS += Gui/libgui.a
@@ -281,6 +292,9 @@
 libfame/libfame.a:
 	$(MAKE) -C libfame
 
+libass/libass.a:
+	$(MAKE) -C libass
+
 libmpdemux/libmpdemux.a:
 	$(MAKE) -C libmpdemux
 
@@ -601,6 +615,8 @@
 vidix/libvidix.a: $(wildcard vidix/*.[ch])
 Gui/libgui.a: $(wildcard Gui/*.[ch] Gui/*/*.[ch] Gui/*/*/*.[ch])
 
+libass/libass.a: $(wildcard libass/*.[ch])
+
 #
 # include dependency files if they exist
 #

Modified: trunk/cfg-common.h
==============================================================================
--- trunk/cfg-common.h	(original)
+++ trunk/cfg-common.h	Fri Jul  7 20:26:51 2006
@@ -296,6 +296,16 @@
  	{"subfont-outline", &subtitle_font_thickness, CONF_TYPE_FLOAT, CONF_RANGE, 0, 8, NULL},
  	{"subfont-autoscale", &subtitle_autoscale, CONF_TYPE_INT, CONF_RANGE, 0, 3, NULL},
 #endif
+#ifdef USE_ASS
+	{"ass", &ass_enabled, CONF_TYPE_FLAG, 0, 0, 1, NULL},
+	{"noass", &ass_enabled, CONF_TYPE_FLAG, 0, 1, 0, NULL},
+	{"ass-font-scale", &ass_font_scale, CONF_TYPE_FLOAT, CONF_RANGE, 0, 100, NULL},
+	{"ass-line-spacing", &ass_line_spacing, CONF_TYPE_FLOAT, CONF_RANGE, -1000, 1000, NULL},
+	{"ass-top-margin", &ass_top_margin, CONF_TYPE_INT, CONF_RANGE, 0, 2000, NULL},
+	{"ass-bottom-margin", &ass_bottom_margin, CONF_TYPE_INT, CONF_RANGE, 0, 2000, NULL},
+	{"embeddedfonts", &extract_embedded_fonts, CONF_TYPE_FLAG, 0, 0, 1, NULL},
+	{"noembeddedfonts", &extract_embedded_fonts, CONF_TYPE_FLAG, 0, 1, 0, NULL},
+#endif
 #ifdef HAVE_FONTCONFIG
 	{"fontconfig", &font_fontconfig, CONF_TYPE_FLAG, 0, 0, 1, NULL},
 	{"nofontconfig", &font_fontconfig, CONF_TYPE_FLAG, 0, 1, 0, NULL},

Modified: trunk/configure
==============================================================================
--- trunk/configure	(original)
+++ trunk/configure	Fri Jul  7 20:26:51 2006
@@ -245,6 +245,7 @@
   --disable-ftp          Disable ftp support [enabled]
   --disable-vstream      Disable tivo vstream client support [autodetect]
   --disable-pthreads     Disable Posix threads support [autodetect]
+  --disable-ass          Disable internal SSA/ASS subtitles support [autodetect]
   --enable-rpath         Enable runtime linker path for extra libs [disabled]
 
 Codecs:
@@ -1691,6 +1692,7 @@
 _musepack=auto
 _vstream=auto
 _pthreads=yes
+_ass=auto
 _rpath=no
 for ac_option do
   case "$ac_option" in
@@ -1975,6 +1977,8 @@
   --disable-vstream)    _vstream=no     ;;
   --enable-pthreads)    _pthreads=yes   ;;
   --disable-pthreads)   _pthreads=no    ;;
+  --enable-ass)         _ass=yes        ;;
+  --disable-ass)        _ass=no         ;;
   --enable-rpath)       _rpath=yes      ;;
   --disable-rpath)      _rpath=no       ;;
 
@@ -5390,6 +5394,35 @@
 fi
 echores "$_fontconfig"
 
+echocheck "SSA/ASS support"
+# libass depends on freetype
+if test "$_freetype" = no ; then
+    _ass=no
+    _res_comment="FreeType support needed"
+fi
+
+if test "$_ass" = auto ; then
+    cat > $TMPC << EOF
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#if ((FREETYPE_MAJOR < 2) || (FREETYPE_MINOR < 1) || ((FREETYPE_MINOR == 1) && (FREETYPE_PATCH < 8)))
+#error "Need FreeType 2.1.8 or newer"
+#endif
+int main() { return 0; }
+EOF
+    _ass=no
+    cc_check `$_freetypeconfig --cflags` `$_freetypeconfig --libs` && tmp_run && _ass=yes
+    if test "$_ass" = no ; then
+        _res_comment="FreeType >= 2.1.8 needed"
+    fi
+fi
+if test "$_ass" = yes ; then
+    _def_ass='#define USE_ASS'
+else
+    _def_ass='#undef USE_ASS'
+fi
+echores "$_ass"
+
 echocheck "fribidi with charsets"
 if test "$_fribidi" = auto ; then
     if ( $_fribidiconfig --version ) >/dev/null 2>&1 ; then
@@ -7517,6 +7550,7 @@
 FREETYPE_LIB = $_ld_freetype
 FONTCONFIG_INC = $_inc_fontconfig
 FONTCONFIG_LIB = $_ld_fontconfig
+CONFIG_ASS = $_ass
 FRIBIDI_INC = $_inc_fribidi
 FRIBIDI_LIB = $_ld_fribidi
 LIBCDIO_INC = $_inc_libcdio
@@ -8118,6 +8152,9 @@
 /* enable Fontconfig support */
 $_def_fontconfig
 
+/* enable SSA/ASS support */
+$_def_ass
+
 /* enable FriBiDi usage */
 $_def_fribidi
 

Added: trunk/libass/Makefile
==============================================================================
--- (empty file)
+++ trunk/libass/Makefile	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,50 @@
+
+include ../config.mak
+
+LIBNAME=libass.a
+
+LIBS=$(LIBNAME)
+
+SRCS=ass.c ass_cache.c ass_fontconfig.c ass_render.c ass_utils.c ass_mp.c
+
+OBJS=$(SRCS:.c=.o)
+
+CFLAGS  = $(OPTFLAGS) \
+          -I. -I.. \
+          -I../libmpcodecs \
+          $(EXTRA_INC) \
+          -D_GNU_SOURCE \
+          $(FREETYPE_INC) \
+          $(FONTCONFIG_INC) \
+
+.SUFFIXES: .c .o
+
+# .PHONY: all clean
+
+.c.o:
+	$(CC) -c $(CFLAGS) -o $@ $<
+
+all:    $(LIBS)
+
+$(LIBNAME):     $(OBJS)
+	$(AR) r $(LIBNAME) $(OBJS)
+	$(RANLIB) $(LIBNAME)
+
+clean:
+	rm -f *.o *.a *~
+
+distclean: clean
+	rm -f .depend
+
+dep:    depend
+
+depend:
+	$(CC) -MM $(CFLAGS) $(SRCS) 1>.depend
+
+#
+# include dependency files if they exist
+#
+ifneq ($(wildcard .depend),)
+include .depend
+endif
+

Added: trunk/libass/ass.c
==============================================================================
--- (empty file)
+++ trunk/libass/ass.c	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,857 @@
+#include "config.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#ifdef HAVE_ENCA
+#include "subreader.h" // for guess_buffer_cp
+#endif
+
+#ifdef USE_ICONV
+#include <iconv.h>
+extern char *sub_cp;
+#endif
+
+#include "mp_msg.h"
+#include "ass.h"
+#include "ass_utils.h"
+#include "libvo/sub.h" // for utf8_get_char
+
+char *get_path(char *);
+
+#define ASS_STYLES_ALLOC 20
+#define ASS_EVENTS_ALLOC 200
+
+void ass_free_track(ass_track_t* track) {
+	int i;
+	
+	if (track->style_format)
+		free(track->style_format);
+	if (track->event_format)
+		free(track->event_format);
+	if (track->styles) {
+		for (i = 0; i < track->n_styles; ++i) {
+			ass_style_t* style = track->styles + i;
+			if (style->Name)
+				free(style->Name);
+			if (style->FontName)
+				free(style->FontName);
+		}
+		free(track->styles);
+	}
+	if (track->events) {
+		for (i = 0; i < track->n_events; ++i) {
+			ass_event_t* event = track->events + i;
+			if (event->Name)
+				free(event->Name);
+			if (event->Effect)
+				free(event->Effect);
+			if (event->Text)
+				free(event->Text);
+		}
+		free(track->events);
+	}
+}
+
+/// \brief Allocate a new style struct
+/// \param track track
+/// \return style id
+int ass_alloc_style(ass_track_t* track) {
+	int sid;
+	
+	assert(track->n_styles <= track->max_styles);
+
+	if (track->n_styles == track->max_styles) {
+		track->max_styles += ASS_STYLES_ALLOC;
+		track->styles = (ass_style_t*)realloc(track->styles, sizeof(ass_style_t)*track->max_styles);
+	}
+	
+	sid = track->n_styles++;
+	memset(track->styles + sid, 0, sizeof(ass_style_t));
+	return sid;
+}
+
+/// \brief Allocate a new event struct
+/// \param track track
+/// \return event id
+int ass_alloc_event(ass_track_t* track) {
+	int eid;
+	
+	assert(track->n_events <= track->max_events);
+
+	if (track->n_events == track->max_events) {
+		track->max_events += ASS_EVENTS_ALLOC;
+		track->events = (ass_event_t*)realloc(track->events, sizeof(ass_event_t)*track->max_events);
+	}
+	
+	eid = track->n_events++;
+	memset(track->events + eid, 0, sizeof(ass_event_t));
+	return eid;
+}
+
+static void free_event(ass_track_t* track, int eid) {
+	if (track->n_events > eid + 1) // not last event
+		memcpy(track->events + eid, track->events + eid + 1, sizeof(ass_event_t) * (track->n_events - eid - 1));
+	track->n_events--;
+}
+
+static int events_compare_f(const void* a_, const void* b_) {
+	ass_event_t* a = (ass_event_t*)a_;
+	ass_event_t* b = (ass_event_t*)b_;
+	if (a->Start < b->Start)
+		return -1;
+	else if (a->Start > b->Start)
+		return 1;
+	else
+		return 0;
+}
+
+/// \brief Sort events by start time
+/// \param tid track id
+static void sort_events(ass_track_t* track) {
+	qsort(track->events, track->n_events, sizeof(ass_event_t), events_compare_f);
+}
+
+// ==============================================================================================
+
+static void skip_spaces(char** str) {
+	char* p = *str;
+	while ((*p==' ') || (*p=='\t'))
+		++p;
+	*str = p;
+}
+
+static void rskip_spaces(char** str, char* limit) {
+	char* p = *str;
+	while ((p >= limit) && ((*p==' ') || (*p=='\t')))
+		--p;
+	*str = p;
+}
+
+/**
+ * \brief find style by name
+ * \param track track
+ * \param name style name
+ * \return index in track->styles
+ * Returnes 0 if no styles found => expects at least 1 style.
+ * Parsing code always adds "Default" style in the end.
+ */
+static int lookup_style(ass_track_t* track, char* name) {
+	int i;
+	for (i=0; i<track->n_styles; ++i) {
+		// FIXME: mb strcasecmp ?
+		if (strcmp(track->styles[i].Name, name) == 0)
+			return i;
+	}
+	i = track->default_style;
+	mp_msg(MSGT_GLOBAL, MSGL_WARN, "[%p] Warning: no style named '%s' found, using '%s'\n", track, name, track->styles[i].Name);
+	return i; // use the first style
+}
+
+static uint32_t string2color(char* p) {
+	uint32_t tmp;
+	(void)strtocolor(&p, &tmp);
+	return tmp;
+}
+
+static long long string2timecode(char* p) {
+	unsigned h, m, s, ms;
+	long long tm;
+	int res = sscanf(p, "%1d:%2d:%2d.%2d", &h, &m, &s, &ms);
+	if (res < 4) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "bad timestamp\n");
+		return 0;
+	}
+	tm = ((h * 60 + m) * 60 + s) * 1000 + ms * 10;
+	return tm;
+}
+
+/**
+ * \brief converts numpad-style align to align.
+ */
+static int numpad2align(int val) {
+	int res, v;
+	v = (val - 1) / 3; // 0, 1 or 2 for vertical alignment
+	if (v != 0) v = 3 - v;
+	res = ((val - 1) % 3) + 1; // horizontal alignment
+	res += v*4;
+	return res;
+}
+
+#define NEXT(str,token) \
+	token = next_token(&str); \
+	if (!token) break;
+
+#define ANYVAL(name,func) \
+	} else if (strcasecmp(tname, #name) == 0) { \
+		target->name = func(token); \
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "%s = %s\n", #name, token);
+#define STRVAL(name) ANYVAL(name,strdup)
+#define COLORVAL(name) ANYVAL(name,string2color)
+#define INTVAL(name) ANYVAL(name,atoi)
+#define FPVAL(name) ANYVAL(name,atof)
+#define TIMEVAL(name) ANYVAL(name,string2timecode)
+#define STYLEVAL(name) \
+	} else if (strcasecmp(tname, #name) == 0) { \
+		target->name = lookup_style(track, token); \
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "%s = %s\n", #name, token);
+
+#define ALIAS(alias,name) \
+	if (strcasecmp(tname, #alias) == 0) {tname = #name;}
+
+static char* next_token(char** str) {
+	char* p = *str;
+	char* start;
+	skip_spaces(&p);
+	if (*p == '\0') {
+		*str = p;
+		return 0;
+	}
+	start = p; // start of the token
+	for (; (*p != '\0') && (*p != ','); ++p) {}
+	if (*p == '\0') {
+		*str = p; // eos found, str will point to '\0' at exit
+	} else {
+		*p = '\0';
+		*str = p + 1; // ',' found, str will point to the next char (beginning of the next token)
+	}
+	--p; // end of current token
+	rskip_spaces(&p, start);
+	if (p < start)
+		p = start; // empty token
+	else
+		++p; // the first space character, or '\0'
+	*p = '\0';
+	return start;
+}
+/**
+ * \brief Parse the tail of Dialogue line
+ * \param track track
+ * \param event parsed data goes here
+ * \param str string to parse, zero-terminated
+ * \param n_ignored number of format options to skip at the beginning
+*/ 
+static int process_event_tail(ass_track_t* track, ass_event_t* event, char* str, int n_ignored)
+{
+	char* token;
+	char* tname;
+	char* p = str;
+	int i;
+	ass_event_t* target = event;
+
+	char* format = strdup(track->event_format);
+	char* q = format; // format scanning pointer
+
+	for (i = 0; i < n_ignored; ++i) {
+		NEXT(q, tname);
+	}
+
+	while (1) {
+		NEXT(q, tname);
+		if (strcasecmp(tname, "Text") == 0) {
+			char* last;
+			event->Text = strdup(p);
+			last = event->Text + strlen(event->Text) - 1;
+			if (*last == '\r')
+				*last = 0;
+			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "Text = %s\n", event->Text);
+			event->Duration -= event->Start;
+			free(format);
+			return 0; // "Text" is always the last
+		}
+		NEXT(p, token);
+
+		ALIAS(End,Duration) // temporarily store end timecode in event->Duration
+		if (0) { // cool ;)
+			STYLEVAL(Style)
+			STRVAL(Name)
+			STRVAL(Effect)
+			INTVAL(MarginL)
+			INTVAL(MarginR)
+			INTVAL(MarginV)
+			TIMEVAL(Start)
+			TIMEVAL(Duration)
+		}
+	}
+	free(format);
+	return 1;
+}
+
+/**
+ * \brief Parse the Style line
+ * \param track track
+ * \param str string to parse, zero-terminated
+ * Allocates a new style struct.
+*/ 
+static int process_style(ass_track_t* track, char *str)
+{
+
+	char* token;
+	char* tname;
+	char* p = str;
+	char* format;
+	char* q; // format scanning pointer
+	int sid;
+	ass_style_t* style;
+	ass_style_t* target;
+
+	if (!track->style_format) {
+		// no style format header
+		// probably an ancient script version
+		if (track->track_type == TRACK_TYPE_SSA)
+			track->style_format = strdup("Name, Fontname, Fontsize, PrimaryColour, SecondaryColour,"
+					"TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline,"
+					"Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding");
+		else
+			track->style_format = strdup("Name, Fontname, Fontsize, PrimaryColour, SecondaryColour,"
+					"OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut,"
+					"ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow,"
+					"Alignment, MarginL, MarginR, MarginV, Encoding");
+	}
+
+	q = format = strdup(track->style_format);
+	
+	mp_msg(MSGT_GLOBAL, MSGL_V, "[%p] Style: %s\n", track, str);
+	
+	sid = ass_alloc_style(track);
+
+	style = track->styles + sid;
+	target = style;
+// fill style with some default values
+	style->ScaleX = 100.;
+	style->ScaleY = 100.;
+	
+	while (1) {
+		NEXT(q, tname);
+		NEXT(p, token);
+		
+//		ALIAS(TertiaryColour,OutlineColour) // ignore TertiaryColour; it appears only in SSA, and is overridden by BackColour
+			
+		if (0) { // cool ;)
+			STRVAL(Name)
+				if ((strcmp(target->Name, "Default")==0) || (strcmp(target->Name, "*Default")==0))
+					track->default_style = sid;
+			STRVAL(FontName)
+			COLORVAL(PrimaryColour)
+			COLORVAL(SecondaryColour)
+			COLORVAL(OutlineColour) // TertiaryColor
+			COLORVAL(BackColour)
+				// SSA uses BackColour for both outline and shadow
+				// this will destroy SSA's TertiaryColour, but i'm not going to use it anyway
+				if (track->track_type == TRACK_TYPE_SSA)
+					target->OutlineColour = target->BackColour;
+			INTVAL(FontSize)
+			INTVAL(Bold)
+			INTVAL(Italic)
+			INTVAL(Underline)
+			INTVAL(StrikeOut)
+			INTVAL(Spacing)
+			INTVAL(Angle)
+			INTVAL(BorderStyle)
+			INTVAL(Alignment)
+				if (track->track_type == TRACK_TYPE_ASS)
+					target->Alignment = numpad2align(target->Alignment);
+			INTVAL(MarginL)
+			INTVAL(MarginR)
+			INTVAL(MarginV)
+			INTVAL(Encoding)
+			FPVAL(ScaleX)
+			FPVAL(ScaleY)
+			FPVAL(Outline)
+			FPVAL(Shadow)
+		}
+	}
+	style->ScaleX /= 100.;
+	style->ScaleY /= 100.;
+	if (!style->Name)
+		style->Name = strdup("Default");
+	if (!style->FontName)
+		style->FontName = strdup("Arial");
+	free(format);
+	return 0;
+	
+}
+
+/**
+ * \brief Parse a header line
+ * \param track track
+ * \param str string to parse, zero-terminated
+*/ 
+static int process_header_line(ass_track_t* track, char *str)
+{
+	static int events_section_started = 0;
+	
+	mp_msg(MSGT_GLOBAL, MSGL_DBG2, "=== Header: %s\n", str);
+	if (strncmp(str, "PlayResX:", 9)==0) {
+		track->PlayResX = atoi(str + 9);
+	} else if (strncmp(str,"PlayResY:", 9)==0) {
+		track->PlayResY = atoi(str + 9);
+	} else if (strncmp(str,"Timer:", 6)==0) {
+		track->Timer = atof(str + 6);
+	} else if (strstr(str,"Styles]")) {
+		events_section_started = 0;
+		if (strchr(str, '+'))
+			track->track_type = TRACK_TYPE_ASS;
+		else
+			track->track_type = TRACK_TYPE_SSA;
+	} else if (strncmp(str,"[Events]", 8)==0) {
+		events_section_started = 1;
+	} else if (strncmp(str,"Format:", 7)==0) {
+		char* p = str + 7;
+		skip_spaces(&p);
+		if (events_section_started) {
+			track->event_format = strdup(p);
+			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "Event format: %s\n", track->event_format);
+		} else {
+			track->style_format = strdup(p);
+			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "Style format: %s\n", track->style_format);
+		}
+	} else if (strncmp(str,"Style:", 6)==0) {
+		char* p = str + 6;
+		skip_spaces(&p);
+		process_style(track, p);
+	} else if (strncmp(str,"WrapStyle:", 10)==0) {
+		track->WrapStyle = atoi(str + 10);
+	}
+	return 0;
+}
+
+/**
+ * \brief Process CodecPrivate section of subtitle stream
+ * \param track track
+ * \param data string to parse
+ * \param size length of data
+ CodecPrivate section contains [Stream Info] and [V4+ Styles] sections
+*/ 
+void ass_process_chunk(ass_track_t* track, char *data, int size)
+{
+	char* str = malloc(size + 1);
+	char* p;
+	int sid;
+
+	memcpy(str, data, size);
+	str[size] = '\0';
+
+	p = str;
+	while(1) {
+		char* q;
+		for (;((*p=='\r')||(*p=='\n'));++p) {}
+		for (q=p; ((*q!='\0')&&(*q!='\r')&&(*q!='\n')); ++q) {};
+		if (q==p)
+			break;
+		if (*q != '\0')
+			*(q++) = '\0';
+		process_header_line(track, p);
+		if (*q == '\0')
+			break;
+		p = q;
+	}
+	free(str);
+
+	// add "Default" style to the end
+	// will be used if track does not contain a default style (or even does not contain styles at all)
+	sid = ass_alloc_style(track);
+	track->styles[sid].Name = strdup("Default");
+	track->styles[sid].FontName = strdup("Arial");
+	
+	if (!track->event_format) {
+		// probably an mkv produced by ancient mkvtoolnix
+		// such files don't have [Events] and Format: headers
+		if (track->track_type == TRACK_TYPE_SSA)
+			track->event_format = strdup("Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text");
+		else
+			track->event_format = strdup("Format: Layer, Start, End, Style, Actor, MarginL, MarginR, MarginV, Effect, Text");
+	}
+}
+
+static int check_duplicate_event(ass_track_t* track, int ReadOrder)
+{
+	int i;
+	for (i = 0; i<track->n_events - 1; ++i) // ignoring last event, it is the one we are comparing with
+		if (track->events[i].ReadOrder == ReadOrder)
+			return 1;
+	return 0;
+}
+
+/**
+ * \brief Process a chunk of subtitle stream data. In matroska, this containes exactly 1 event (or a commentary)
+ * \param track track
+ * \param data string to parse
+ * \param size length of data
+ * \param timecode starting time of the event (milliseconds)
+ * \param duration duration of the event (milliseconds)
+*/ 
+void ass_process_line(ass_track_t* track, char *data, int size, long long timecode, long long duration)
+{
+	char* str;
+	int eid;
+	char* p;
+	char* token;
+	ass_event_t* event;
+
+	if (!track->event_format) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "Event format header missing\n");
+		return;
+	}
+	
+	str = malloc(size + 1);
+	memcpy(str, data, size);
+	str[size] = '\0';
+	mp_msg(MSGT_GLOBAL, MSGL_V, "\nline at timecode %lld, duration %lld: \n%s\n", timecode, duration, str);
+
+	eid = ass_alloc_event(track);
+	event = track->events + eid;
+
+	p = str;
+	
+	do { 
+		NEXT(p, token);
+		event->ReadOrder = atoi(token);
+		if (check_duplicate_event(track, event->ReadOrder))
+			break;
+
+		NEXT(p, token);
+		event->Layer = atoi(token);
+
+		process_event_tail(track, event, p, 3);
+
+		event->Start = timecode;
+		event->Duration = duration;
+		
+		free(str);
+		return;
+//		dump_events(tid);
+	} while (0);
+	// some error
+	free_event(track, eid);
+	free(str);
+}
+
+/**
+ * \brief Process a line from external file.
+ * \param track track
+ * \param str string to parse
+ * \param size length of data
+*/ 
+static void ass_process_external_line(ass_track_t* track, char *str, int size)
+{
+	int eid;
+	ass_event_t* event;
+
+	eid = ass_alloc_event(track);
+	event = track->events + eid;
+
+	if (strncmp("Dialogue:", str, 9) != 0)
+		return;
+
+	str += 9;
+	while (*str == ' ') {++str;}
+	
+	process_event_tail(track, event, str, 0);
+}
+
+#ifdef USE_ICONV
+/** \brief recode buffer to utf-8
+ * constraint: sub_cp != 0
+ * \param data pointer to text buffer
+ * \param size buffer size
+ * \return a pointer to recoded buffer, caller is responsible for freeing it
+**/
+static char* sub_recode(char* data, size_t size)
+{
+	static iconv_t icdsc = (iconv_t)(-1);
+	char* tocp = "UTF-8";
+	char* outbuf;
+	assert(sub_cp);
+
+	{
+		char* cp_tmp = sub_cp;
+#ifdef HAVE_ENCA
+		char enca_lang[3], enca_fallback[100];
+		if (sscanf(sub_cp, "enca:%2s:%99s", enca_lang, enca_fallback) == 2
+				|| sscanf(sub_cp, "ENCA:%2s:%99s", enca_lang, enca_fallback) == 2) {
+			cp_tmp = guess_buffer_cp((unsigned char*)data, size, enca_lang, enca_fallback);
+		}
+#endif
+		if ((icdsc = iconv_open (tocp, cp_tmp)) != (iconv_t)(-1)){
+			mp_msg(MSGT_SUBREADER,MSGL_V,"LIBSUB: opened iconv descriptor.\n");
+		} else
+			mp_msg(MSGT_SUBREADER,MSGL_ERR,"LIBSUB: error opening iconv descriptor.\n");
+#ifdef HAVE_ENCA
+		if (cp_tmp) free(cp_tmp);
+#endif
+	}
+
+	{
+		size_t osize = size;
+		size_t ileft = size;
+		size_t oleft = size - 1;
+		char* ip;
+		char* op;
+		size_t rc;
+		
+		outbuf = malloc(size);
+		ip = data;
+		op = outbuf;
+		
+		while (ileft) {
+			rc = iconv(icdsc, &ip, &ileft, &op, &oleft);
+			if (rc == (size_t)(-1)) {
+				if (errno == E2BIG) {
+					int offset = op - outbuf;
+					outbuf = (char*)realloc(outbuf, osize + size);
+					op = outbuf + offset;
+					osize += size;
+					oleft += size;
+				} else {
+					mp_msg(MSGT_SUBREADER, MSGL_WARN, "LIBSUB: error recoding file.\n");
+					return NULL;
+				}
+			}
+		}
+		outbuf[osize - oleft - 1] = 0;
+	}
+
+	if (icdsc != (iconv_t)(-1)) {
+		(void)iconv_close(icdsc);
+		icdsc = (iconv_t)(-1);
+		mp_msg(MSGT_SUBREADER,MSGL_V,"LIBSUB: closed iconv descriptor.\n");
+	}
+	
+	return outbuf;
+}
+#endif // ICONV
+
+/**
+ * \brief Read subtitles from file.
+ * \param fname file name
+ * \return newly allocated track
+*/ 
+ass_track_t* ass_read_file(char* fname)
+{
+	int res;
+	long sz;
+	long bytes_read;
+	char* buf;
+	char* p;
+	int events_reached;
+	ass_track_t* track;
+	
+	FILE* fp = fopen(fname, "rb");
+	if (!fp) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "ass_read_file(%s): fopen failed\n", fname);
+		return 0;
+	}
+	res = fseek(fp, 0, SEEK_END);
+	if (res == -1) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "ass_read_file(%s): fseek failed\n", fname);
+		fclose(fp);
+		return 0;
+	}
+	
+	sz = ftell(fp);
+	rewind(fp);
+
+	if (sz > 10*1024*1024) {
+		mp_msg(MSGT_GLOBAL, MSGL_INFO, "ass_read_file(%s): Refusing to load subtitles larger than 10M\n", fname);
+		fclose(fp);
+		return 0;
+	}
+	
+	mp_msg(MSGT_GLOBAL, MSGL_V, "file size: %ld\n", sz);
+	
+	buf = malloc(sz + 1);
+	assert(buf);
+	bytes_read = 0;
+	do {
+		res = fread(buf + bytes_read, 1, sz - bytes_read, fp);
+		if (res <= 0) {
+			mp_msg(MSGT_GLOBAL, MSGL_INFO, "Read failed, %d: %s\n", errno, strerror(errno));
+			fclose(fp);
+			free(buf);
+			return 0;
+		}
+		bytes_read += res;
+	} while (sz - bytes_read > 0);
+	buf[sz] = '\0';
+	fclose(fp);
+	
+#ifdef USE_ICONV
+	if (sub_cp) {
+		char* tmpbuf = sub_recode(buf, sz);
+		free(buf);
+		if (!tmpbuf)
+			return 0;
+		buf = tmpbuf;
+	}
+#endif
+	
+	track = ass_new_track();
+	track->name = strdup(fname);
+	
+	// process header
+	events_reached = 0;
+	p = buf;
+	while (p && (*p)) {
+		while (*p == '\n') {++p;}
+		if (strncmp(p, "[Events]", 8) == 0) {
+			events_reached = 1;
+		} else if ((strncmp(p, "Format:", 7) == 0) && (events_reached)) {
+			p = strchr(p, '\n');
+			if (p == 0) {
+				mp_msg(MSGT_GLOBAL, MSGL_WARN, "Incomplete subtitles\n");
+				free(buf);
+				return 0;
+			}
+			ass_process_chunk(track, buf, p - buf + 1);
+			++p;
+			break;
+		}
+		p = strchr(p, '\n');
+	}
+	// process events
+	while (p && (*p)) {
+		char* next;
+		int len;
+		while (*p == '\n') {++p;}
+		next = strchr(p, '\n');
+		len = 0;
+		if (next) {
+			len = next - p;
+			*next = 0;
+		} else {
+			len = strlen(p);
+		}
+		ass_process_external_line(track, p, len);
+		if (next) {
+			p = next + 1;
+			continue;
+		} else
+			break;
+	}
+	
+	free(buf);
+
+	if (!events_reached) {
+		ass_free_track(track);
+		return 0;
+	}
+
+	mp_msg(MSGT_GLOBAL, MSGL_INFO, "LIBASS: added subtitle file: %s (%d styles, %d events)\n", fname, track->n_styles, track->n_events);
+	
+	sort_events(track);
+		
+//	dump_events(forced_tid);
+	return track;
+}
+
+static char* validate_fname(char* name)
+{
+	char* fname;
+	char* p;
+	char* q;
+	unsigned code;
+	int sz = strlen(name);
+
+	q = fname = malloc(sz + 1);
+	p = name;
+	while (*p) {
+		code = utf8_get_char(&p);
+		if (code == 0)
+			break;
+		if (	(code > 0x7F) ||
+			(code == '\\') ||
+			(code == '/') ||
+			(code == ':') ||
+			(code == '*') ||
+			(code == '?') ||
+			(code == '<') ||
+			(code == '>') ||
+			(code == '|') ||
+			(code == 0))
+		{
+			*q++ = '_';
+		} else {
+			*q++ = code;
+		}
+		if (p - name > sz)
+			break;
+	}
+	*q = 0;
+	return fname;
+}
+
+/**
+ * \brief Process embedded matroska font. Saves it to ~/.mplayer/fonts.
+ * \param name attachment name
+ * \param data binary font data
+ * \param data_size data size
+*/ 
+void ass_process_font(const char* name, char* data, int data_size)
+{
+	char buf[1000];
+	FILE* fp = 0;
+	int rc;
+	struct stat st;
+	char* fname;
+
+	char* fonts_dir = get_path("fonts");
+	rc = stat(fonts_dir, &st);
+	if (rc) {
+		int res;
+#ifndef __MINGW32__
+		res = mkdir(fonts_dir, 0700);
+#else
+		res = mkdir(fonts_dir);
+#endif
+		if (res) {
+			mp_msg(MSGT_GLOBAL, MSGL_WARN, "Failed to create: %s\n", fonts_dir);
+		}
+	} else if (!S_ISDIR(st.st_mode)) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "Not a directory: %s\n", fonts_dir);
+	}
+	
+	fname = validate_fname((char*)name);
+
+	snprintf(buf, 1000, "%s/%s", fonts_dir, fname);
+	free(fname);
+	free(fonts_dir);
+
+	fp = fopen(buf, "wb");
+	if (!fp) return;
+
+	fwrite(data, data_size, 1, fp);
+	fclose(fp);
+}
+
+long long ass_step_sub(ass_track_t* track, long long now, int movement) {
+	int i;
+
+	if (movement == 0) return 0;
+	if (track->n_events == 0) return 0;
+	
+	if (movement < 0)
+		for (i = 0; (i < track->n_events) && ((long long)(track->events[i].Start + track->events[i].Duration) <= now); ++i) {}
+	else
+		for (i = track->n_events - 1; (i >= 0) && ((long long)(track->events[i].Start) > now); --i) {}
+	
+	// -1 and n_events are ok
+	assert(i >= -1); assert(i <= track->n_events);
+	i += movement;
+	if (i < 0) i = 0;
+	if (i >= track->n_events) i = track->n_events - 1;
+	return ((long long)track->events[i].Start) - now;
+}
+
+ass_track_t* ass_new_track(void) {
+	ass_track_t* track = calloc(1, sizeof(ass_track_t));
+	return track;
+}
+

Added: trunk/libass/ass.h
==============================================================================
--- (empty file)
+++ trunk/libass/ass.h	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,156 @@
+#ifndef __ASS_H__
+#define __ASS_H__
+
+#include "ass_types.h"
+
+/// Libass "library object". Contents are private.
+typedef struct ass_instance_s ass_instance_t;
+
+/// used in ass_configure
+typedef struct ass_settings_s {
+	int frame_width;
+	int frame_height;
+	double font_size_coeff; // font size multiplier
+	double line_spacing; // additional line spacing (in frame pixels)
+	int top_margin; // height of top margin. Everything except toptitles is shifted down by top_margin.
+	int bottom_margin; // height of bottom margin. (frame_height - top_margin - bottom_margin) is original video height.
+	double aspect; // frame aspect ratio, d_width / d_height.
+} ass_settings_t;
+
+/// a linked list of images produced by ass renderer
+typedef struct ass_image_s {
+	int w, h; // bitmap width/height
+	int stride; // bitmap stride
+	unsigned char* bitmap; // 1bpp stride*h alpha buffer
+	uint32_t color; // RGBA
+	int dst_x, dst_y; // bitmap placement inside the video frame
+
+	struct ass_image_s* next; // linked list
+} ass_image_t;
+
+/**
+ * \brief initialize the library
+ * \return library handle or NULL if failed
+ */
+ass_instance_t* ass_init(void);
+
+/**
+ * \brief finalize the library
+ * \param priv library handle
+ */
+void ass_done(ass_instance_t* priv);
+
+/**
+ * \brief configure the library
+ * \param priv library handle
+ * \param config struct with configuration parameters. Caller is free to reuse it after this function returns.
+ */
+void ass_configure(ass_instance_t* priv, const ass_settings_t* config);
+
+/**
+ * \brief start rendering a frame
+ * \param priv library
+ * \param track subtitle track
+ * \param now video timestamp in milliseconds
+ */
+int ass_start_frame(ass_instance_t *priv, ass_track_t* track, long long now);
+
+/**
+ * \brief render a single event
+ * uses library, track and timestamp from the previous call to ass_start_frame
+ */
+int ass_render_event(ass_event_t* event);
+
+/**
+ * \brief done rendering frame, give out the results
+ * \return a list of images for blending
+ */
+ass_image_t* ass_end_frame(void); // returns linked list of images to render
+
+/**
+ * \brief render a frame, producing a list of ass_image_t
+ * \param priv library
+ * \param track subtitle track
+ * \param now video timestamp in milliseconds
+ * This function is equivalent to 
+ *   ass_start_frame()
+ *   for events: start <= now < end:
+ *     ass_render_event()
+ *   ass_end_frame()
+ */
+ass_image_t* ass_render_frame(ass_instance_t *priv, ass_track_t* track, long long now);
+
+
+// The following functions operate on track objects and do not need an ass_instance //
+
+/**
+ * \brief allocate a new empty track object
+ * \return pointer to empty track
+ */
+ass_track_t* ass_new_track(void);
+
+/**
+ * \brief deallocate track and all its child objects (styles and events)
+ * \param track track to deallocate
+ */
+void ass_free_track(ass_track_t* track);
+
+/**
+ * \brief allocate new style
+ * \param track track
+ * \return newly allocated style id
+ */
+int ass_alloc_style(ass_track_t* track);
+
+/**
+ * \brief allocate new event
+ * \param track track
+ * \return newly allocated event id
+ */
+int ass_alloc_event(ass_track_t* track);
+
+/**
+ * \brief Process Codec Private section of subtitle stream
+ * \param track target track
+ * \param data string to parse
+ * \param size length of data
+ */
+void ass_process_chunk(ass_track_t* track, char *data, int size);
+
+/**
+ * \brief Process a chunk of subtitle stream data. In matroska, this containes exactly 1 event (or a commentary)
+ * \param track track
+ * \param data string to parse
+ * \param size length of data
+ * \param timecode starting time of the event (milliseconds)
+ * \param duration duration of the event (milliseconds)
+*/
+void ass_process_line(ass_track_t* track, char *data, int size, long long timecode, long long duration);
+
+/**
+ * \brief Read subtitles from file.
+ * \param fname file name
+ * \return newly allocated track
+*/
+ass_track_t* ass_read_file(char* fname);
+
+/**
+ * \brief Process embedded matroska font. Saves it to ~/.mplayer/fonts.
+ * \param name attachment name
+ * \param data binary font data
+ * \param data_size data size
+*/
+void ass_process_font(const char* name, char* data, int data_size);
+
+/**
+ * \brief Calculates timeshift from now to the start of some other subtitle event, depending on movement parameter
+ * \param track subtitle track
+ * \param now current time, ms
+ * \param movement how many events to skip from the one currently displayed
+ * +2 means "the one after the next", -1 means "previous"
+ * \return timeshift, ms
+ */
+long long ass_step_sub(ass_track_t* track, long long now, int movement);
+
+#endif
+

Added: trunk/libass/ass_cache.c
==============================================================================
--- (empty file)
+++ trunk/libass/ass_cache.c	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,209 @@
+#include "config.h"
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#include <assert.h>
+
+#include "mp_msg.h"
+#include "ass_fontconfig.h"
+#include "ass_cache.h"
+
+
+typedef struct face_cache_item_s {
+	face_desc_t desc;
+	char* path;
+	int index;
+	FT_Face face;
+} face_cache_item_t;
+
+#define MAX_FACE_CACHE_SIZE 100
+
+static face_cache_item_t* face_cache;
+static int face_cache_size;
+
+extern int no_more_font_messages;
+
+static int font_compare(face_desc_t* a, face_desc_t* b) {
+	if (strcmp(a->family, b->family) != 0)
+		return 0;
+	if (a->bold != b->bold)
+		return 0;
+	if (a->italic != b->italic)
+		return 0;
+	return 1;
+}
+
+/**
+ * \brief Get a face object, either from cache or created through FreeType+FontConfig.
+ * \param library FreeType library object
+ * \param fontconfig_priv fontconfig private data
+ * \param desc required face description
+ * \param face out: the face object
+*/ 
+int ass_new_face(FT_Library library, void* fontconfig_priv, face_desc_t* desc, /*out*/ FT_Face* face)
+{
+	FT_Error error;
+	int i;
+	char* path;
+	int index;
+	face_cache_item_t* item;
+	
+	for (i=0; i<face_cache_size; ++i)
+		if (font_compare(desc, &(face_cache[i].desc))) {
+			*face = face_cache[i].face;
+			return 0;
+		}
+
+	if (face_cache_size == MAX_FACE_CACHE_SIZE) {
+		mp_msg(MSGT_GLOBAL, MSGL_FATAL, "Too many fonts\n");
+		return 1;
+	}
+
+	path = fontconfig_select(fontconfig_priv, desc->family, desc->bold, desc->italic, &index);
+	
+	error = FT_New_Face(library, path, index, face);
+	if (error) {
+		if (!no_more_font_messages)
+			mp_msg(MSGT_GLOBAL, MSGL_WARN, "Error opening font: %s, %d\n", path, index);
+		no_more_font_messages = 1;
+		return 1;
+	}
+	
+	item = face_cache + face_cache_size;
+	item->path = strdup(path);
+	item->index = index;
+	item->face = *face;
+	memcpy(&(item->desc), desc, sizeof(face_desc_t));
+	face_cache_size++;
+	return 0;
+}
+
+void ass_face_cache_init(void)
+{
+	face_cache = calloc(MAX_FACE_CACHE_SIZE, sizeof(face_cache_item_t));
+	face_cache_size = 0;
+}
+
+void ass_face_cache_done(void)
+{
+	int i;
+	for (i = 0; i < face_cache_size; ++i) {
+		face_cache_item_t* item = face_cache + i;
+		if (item->face) FT_Done_Face(item->face);
+		if (item->path) free(item->path);
+		// FIXME: free desc ?
+	}
+	free(face_cache);
+	face_cache_size = 0;
+}
+
+//---------------------------------
+// glyph cache
+
+#define GLYPH_HASH_SIZE (0xFFFF + 13)
+
+typedef struct glyph_hash_item_s {
+	glyph_hash_key_t key;
+	glyph_hash_val_t val;
+	struct glyph_hash_item_s* next;
+} glyph_hash_item_t;
+
+typedef glyph_hash_item_t* glyph_hash_item_p;
+
+static glyph_hash_item_p* glyph_hash_root;
+static int glyph_hash_size;
+
+static int glyph_compare(glyph_hash_key_t* a, glyph_hash_key_t* b) {
+	if (memcmp(a, b, sizeof(glyph_hash_key_t)) == 0)
+		return 1;
+	else
+		return 0;
+}
+
+static unsigned glyph_hash(glyph_hash_key_t* key) {
+	unsigned val = 0;
+	unsigned i;
+	for (i = 0; i < sizeof(key->face); ++i)
+		val += *(unsigned char *)(&(key->face) + i);
+	val <<= 21;
+	
+	if (key->bitmap)   val &= 0x80000000;
+	val += key->index;
+	val += key->size << 8;
+	val += key->outline << 3;
+	val += key->advance.x << 10;
+	val += key->advance.y << 16;
+	val += key->bold << 1;
+	val += key->italic << 20;
+	return val;
+}
+
+/**
+ * \brief Add a glyph to glyph cache.
+ * \param key hash key
+ * \param val hash val: 2 bitmap glyphs + some additional info
+*/ 
+void cache_add_glyph(glyph_hash_key_t* key, glyph_hash_val_t* val)
+{
+	unsigned hash = glyph_hash(key);
+	glyph_hash_item_t** next = glyph_hash_root + (hash % GLYPH_HASH_SIZE);
+	while (*next) {
+		if (glyph_compare(key, &((*next)->key)))
+			return;
+		next = &((*next)->next);
+		assert(next);
+	}
+	(*next) = malloc(sizeof(glyph_hash_item_t));
+//	(*next)->desc = glyph_key_copy(key, &((*next)->key));
+	memcpy(&((*next)->key), key, sizeof(glyph_hash_key_t));
+	memcpy(&((*next)->val), val, sizeof(glyph_hash_val_t));
+	(*next)->next = 0;
+
+	glyph_hash_size ++;
+/*	if (glyph_hash_size  && (glyph_hash_size % 25 == 0)) {
+		printf("\nGlyph cache: %d entries, %d bytes\n", glyph_hash_size, glyph_hash_size * sizeof(glyph_hash_item_t));
+	} */
+}
+
+/**
+ * \brief Get a glyph from glyph cache.
+ * \param key hash key
+ * \return requested hash val or 0 if not found
+*/ 
+glyph_hash_val_t* cache_find_glyph(glyph_hash_key_t* key)
+{
+	unsigned hash = glyph_hash(key);
+	glyph_hash_item_t* item = glyph_hash_root[hash % GLYPH_HASH_SIZE];
+	while (item) {
+		if (glyph_compare(key, &(item->key))) {
+			return &(item->val);
+		}
+		item = item->next;
+	}
+	return 0;
+}
+
+void ass_glyph_cache_init(void)
+{
+	glyph_hash_root = calloc(GLYPH_HASH_SIZE, sizeof(glyph_hash_item_p));
+	glyph_hash_size = 0;
+}
+
+void ass_glyph_cache_done(void)
+{
+	int i;
+	for (i = 0; i < GLYPH_HASH_SIZE; ++i) {
+		glyph_hash_item_t* item = glyph_hash_root[i];
+		while (item) {
+			glyph_hash_item_t* next = item->next;
+			if (item->val.glyph) FT_Done_Glyph(item->val.glyph);
+			if (item->val.outline_glyph) FT_Done_Glyph(item->val.outline_glyph);
+			free(item);
+			item = next;
+		}
+	}
+	free(glyph_hash_root);
+	glyph_hash_size = 0;
+}
+

Added: trunk/libass/ass_cache.h
==============================================================================
--- (empty file)
+++ trunk/libass/ass_cache.h	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,50 @@
+#ifndef __ASS_CACHE_H__
+#define __ASS_CACHE_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_STROKER_H
+#include FT_GLYPH_H
+
+// font cache
+typedef struct face_desc_s {
+	char* family;
+	unsigned bold;
+	unsigned italic;
+} face_desc_t;
+
+void ass_face_cache_init(void);
+int ass_new_face(FT_Library library, void* fontconfig_priv, face_desc_t* desc, /*out*/ FT_Face* face);
+void ass_face_cache_done(void);
+
+
+// describes a glyph; glyphs with equivalents structs are considered identical
+typedef struct glyph_hash_key_s {
+	char bitmap; // bool : true = bitmap, false = outline
+	FT_Face face;
+	int size; // font size
+	int index; // glyph index in the face
+	unsigned outline; // border width, 16.16 fixed point value
+	int bold, italic;
+
+	// the following affects bitmap glyphs only
+	unsigned scale_x, scale_y; // 16.16
+	int angle; // signed 16.16
+	
+	FT_Vector advance; // subpixel shift vector
+} glyph_hash_key_t;
+
+typedef struct glyph_hash_val_s {
+	FT_Glyph glyph; // the actual glyphs
+	FT_Glyph outline_glyph;
+	FT_BBox bbox_scaled; // bbox after scaling, but before rotation
+	FT_Vector advance; // 26.6, advance distance to the next glyph in line
+} glyph_hash_val_t;
+
+void ass_glyph_cache_init(void);
+void cache_add_glyph(glyph_hash_key_t* key, glyph_hash_val_t* val);
+glyph_hash_val_t* cache_find_glyph(glyph_hash_key_t* key);
+void ass_glyph_cache_done(void);
+
+#endif
+

Added: trunk/libass/ass_fontconfig.c
==============================================================================
--- (empty file)
+++ trunk/libass/ass_fontconfig.c	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,192 @@
+#include "config.h"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <assert.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include "mp_msg.h"
+#include "ass_fontconfig.h"
+
+#ifdef HAVE_FONTCONFIG
+#include <fontconfig/fontconfig.h>
+#endif
+
+struct fc_instance_s {
+#ifdef HAVE_FONTCONFIG
+	FcConfig* config;
+#endif
+	char* family_default;
+	char* path_default;
+	int index_default;
+};
+
+extern int no_more_font_messages;
+
+#ifdef HAVE_FONTCONFIG
+/**
+ * \brief Low-level font selection.
+ * \param priv private data
+ * \param family font family
+ * \param bold font weight value
+ * \param italic font slant value
+ * \param index out: font index inside a file
+ * \return font file path
+*/ 
+static char* _select_font(fc_instance_t* priv, const char* family, unsigned bold, unsigned italic, int* index)
+{
+	FcBool rc;
+	FcResult result;
+	FcPattern *pat, *rpat;
+	int val_i;
+	FcChar8* val_s;
+	char buf[2000];
+	
+	*index = 0;
+
+	snprintf(buf, 2000, "%s:outline=True:slant=%u:weight=%u", family, italic, bold);
+
+	pat = FcNameParse((const FcChar8*)buf);
+	if (!pat)
+		return 0;
+	
+	FcDefaultSubstitute(pat);
+	
+	rc = FcConfigSubstitute(priv->config, pat, FcMatchPattern);
+	if (!rc)
+		return 0;
+	
+	rpat = FcFontMatch(priv->config, pat, &result);
+	if (!rpat)
+		return 0;
+	
+	result = FcPatternGetInteger(rpat, FC_INDEX, 0, &val_i);
+	if (result != FcResultMatch)
+		return 0;
+	*index = val_i;
+
+	result = FcPatternGetString(rpat, FC_FAMILY, 0, &val_s);
+	if (result != FcResultMatch)
+		return 0;
+
+	if (strcasecmp((const char*)val_s, family) != 0)
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "fontconfig: selected font family is not the requested one: '%s' != '%s'\n",
+				(const char*)val_s, family);
+
+	result = FcPatternGetString(rpat, FC_FILE, 0, &val_s);
+	if (result != FcResultMatch)
+		return 0;
+	
+	return strdup((const char*)val_s);
+}
+
+/**
+ * \brief Find a font. Use default family or path if necessary.
+ * \param priv_ private data
+ * \param family font family
+ * \param bold font weight value
+ * \param italic font slant value
+ * \param index out: font index inside a file
+ * \return font file path
+*/ 
+char* fontconfig_select(fc_instance_t* priv, const char* family, unsigned bold, unsigned italic, int* index)
+{
+	char* res = 0;
+	if (family && *family)
+		res = _select_font(priv, family, bold, italic, index);
+	if (!res && priv->family_default) {
+		res = _select_font(priv, priv->family_default, bold, italic, index);
+		if (res && !no_more_font_messages)
+			mp_msg(MSGT_GLOBAL, MSGL_WARN, "fontconfig_select: using default font family: (%s, %d, %d) -> %s, %d\n", 
+					family, bold, italic, res, *index);
+	}
+	if (!res && priv->path_default) {
+		res = priv->path_default;
+		*index = priv->index_default;
+		if (!no_more_font_messages)
+			mp_msg(MSGT_GLOBAL, MSGL_WARN, "fontconfig_select: using default font: (%s, %d, %d) -> %s, %d\n",
+					family, bold, italic, res, *index);
+	}
+	if (!res) {
+		res = _select_font(priv, "Arial", bold, italic, index);
+		if (res && !no_more_font_messages)
+			mp_msg(MSGT_GLOBAL, MSGL_WARN, "fontconfig_select: using 'Arial' font family: (%s, %d, %d) -> %s, %d\n",
+					family, bold, italic, res, *index);
+	}
+	if (res)
+		mp_msg(MSGT_GLOBAL, MSGL_V, "fontconfig_select: (%s, %d, %d) -> %s, %d\n", 
+				family, bold, italic, res, *index);
+	return res;
+}
+
+/**
+ * \brief Init fontconfig.
+ * \param dir additional directoryu for fonts
+ * \param family default font family
+ * \param path default font path
+ * \return pointer to fontconfig private data
+*/ 
+fc_instance_t* fontconfig_init(const char* dir, const char* family, const char* path)
+{
+	int rc;
+	struct stat st;
+	fc_instance_t* priv = calloc(1, sizeof(fc_instance_t));
+	
+	rc = FcInit();
+	assert(rc);
+
+	priv->config = FcConfigGetCurrent();
+	if (!priv->config) {
+		mp_msg(MSGT_GLOBAL, MSGL_FATAL, "FcInitLoadConfigAndFonts failed\n");
+		return 0;
+	}
+
+	rc = FcConfigAppFontAddDir(priv->config, (const FcChar8*)dir);
+	if (!rc) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "FcConfigAppFontAddDir failed\n");
+	}
+
+	priv->family_default = family ? strdup(family) : 0;
+	priv->index_default = 0;
+	
+	rc = stat(path, &st);
+	if (!rc && S_ISREG(st.st_mode))
+		priv->path_default = path ? strdup(path) : 0;
+	else
+		priv->path_default = 0;
+
+	return priv;
+}
+
+#else
+
+char* fontconfig_select(fc_instance_t* priv, const char* family, unsigned bold, unsigned italic, int* index)
+{
+	*index = priv->index_default;
+	return priv->path_default;
+}
+
+fc_instance_t* fontconfig_init(const char* dir, const char* family, const char* path)
+{
+	mp_msg(MSGT_GLOBAL, MSGL_WARN, "Fontconfig disabled, only default font will be used\n");
+	
+	fc_instance_t* priv = calloc(1, sizeof(fc_instance_t));
+	
+	priv->path_default = strdup(path);
+	priv->index_default = 0;
+	return priv;
+}
+
+#endif
+
+void fontconfig_done(fc_instance_t* priv)
+{
+	// don't call FcFini() here, library can still be used by some code
+	if (priv && priv->path_default) free(priv->path_default);
+	if (priv && priv->family_default) free(priv->family_default);
+	if (priv) free(priv);
+}
+
+

Added: trunk/libass/ass_fontconfig.h
==============================================================================
--- (empty file)
+++ trunk/libass/ass_fontconfig.h	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,11 @@
+#ifndef __ASS_FONTCONFIG_H__
+#define __ASS_FONTCONFIG_H__
+
+typedef struct fc_instance_s fc_instance_t;
+
+fc_instance_t* fontconfig_init(const char* dir, const char* family, const char* path);
+char* fontconfig_select(fc_instance_t* priv, const char* family, unsigned bold, unsigned italic, int* index);
+void fontconfig_done(fc_instance_t* priv);
+
+#endif
+

Added: trunk/libass/ass_mp.c
==============================================================================
--- (empty file)
+++ trunk/libass/ass_mp.c	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,10 @@
+#include "ass_mp.h"
+
+// libass-related command line options
+int ass_enabled = 0;
+float ass_font_scale = 1.;
+float ass_line_spacing = 0.;
+int ass_top_margin = 0;
+int ass_bottom_margin = 0;
+int extract_embedded_fonts = 0;
+

Added: trunk/libass/ass_mp.h
==============================================================================
--- (empty file)
+++ trunk/libass/ass_mp.h	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,12 @@
+#ifndef __ASS_OPTIONS_H__
+#define __ASS_OPTIONS_H__
+
+extern int ass_enabled;
+extern float ass_font_scale;
+extern float ass_line_spacing;
+extern int ass_top_margin;
+extern int ass_bottom_margin;
+extern int extract_embedded_fonts;
+
+#endif
+

Added: trunk/libass/ass_render.c
==============================================================================
--- (empty file)
+++ trunk/libass/ass_render.c	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,1766 @@
+#include "config.h"
+
+#include <assert.h>
+#include <math.h>
+#include <stdint.h>
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_STROKER_H
+#include FT_GLYPH_H
+#include FT_SYNTHESIS_H
+
+#include "mp_msg.h"
+
+#include "ass.h"
+#include "ass_cache.h"
+#include "ass_utils.h"
+#include "ass_fontconfig.h"
+
+#include "libvo/sub.h" // for utf8_get_char
+
+#define MAX_GLYPHS 1000
+#define MAX_LINES 100
+
+char *get_path(char *);
+
+extern char *font_name;
+#ifdef HAVE_FONTCONFIG
+extern int font_fontconfig;
+#else
+static int font_fontconfig = 0;
+#endif
+
+struct ass_instance_s {
+	FT_Library library;
+	fc_instance_t* fontconfig_priv;
+	ass_settings_t settings;
+
+	ass_image_t* images_root; // rendering result is stored here
+	int n_images;
+	int max_images;
+};
+
+int no_more_font_messages = 0;  // don't print font warnings
+
+typedef enum {EF_NONE = 0, EF_KARAOKE, EF_KARAOKE_KF, EF_KARAOKE_KO} effect_t;
+
+// describes a glyph
+// glyph_info_t and text_info_t are used for text centering and word-wrapping operations
+typedef struct glyph_info_s {
+	unsigned symbol;
+	FT_Glyph glyph;
+	FT_Glyph outline_glyph;
+	FT_BBox bbox;
+	FT_Vector pos;
+	char linebreak; // the first (leading) glyph of some line ?
+	uint32_t c1, c2, c3, c4; // colors
+	char bitmap; // bool
+	FT_Vector advance; // 26.6
+	effect_t effect_type;
+	int effect_timing;
+	int asc, desc; // font max ascender and descender
+//	int height;
+	
+	glyph_hash_key_t hash_key;
+} glyph_info_t;
+
+typedef struct line_info_s {
+	int asc, desc;
+} line_info_t;
+
+typedef struct text_info_s {
+	glyph_info_t* glyphs;
+	int length;
+	line_info_t lines[MAX_LINES];
+	int n_lines;
+	int height;
+} text_info_t;
+
+
+// Renderer state.
+// Values like current font face, color, screen position, clipping and so on are stored here.
+typedef struct render_context_s {
+	ass_event_t* event;
+	ass_style_t* style;
+	
+	FT_Face face;
+	char* font_path;
+	int font_size;
+	
+	FT_Stroker stroker;
+	int alignment; // alignment overrides go here; if zero, style value will be used
+	double rotation;
+	enum {	EVENT_NORMAL, // "normal" top-, sub- or mid- title
+		EVENT_POSITIONED // happens after pos(,), margins are ignored
+		} evt_type;
+	int pos_x, pos_y; // position
+	int org_x, org_y; // origin
+	double scale_x, scale_y;
+	int hspacing; // distance between letters, in pixels
+	double border; // outline width
+	uint32_t c1, c2, c3, c4; // colors(Primary, Secondary, so on) in RGBA
+	int clip_x0, clip_y0, clip_x1, clip_y1;
+	char detect_collisions;
+
+	effect_t effect_type;
+	int effect_timing;
+
+	// face properties
+	char* family;
+	unsigned bold;
+	unsigned italic;
+	
+} render_context_t;
+
+// frame-global data
+typedef struct frame_context_s {
+	ass_instance_t* ass_priv;
+	int width, height; // screen dimensions
+	int orig_height; // frame height ( = screen height - margins )
+	ass_track_t* track;
+	int add_bottom_margin; // additional margin, used to shift subtitles in case of collision
+	int add_top_margin;
+	long long time; // frame's timestamp, ms
+	double font_scale_x; // x scale applied to all glyphs to preserve text aspect ratio
+} frame_context_t;
+
+static ass_instance_t* ass_instance;
+static ass_settings_t* global_settings;
+static text_info_t text_info;
+static render_context_t render_context;
+static frame_context_t frame_context;
+
+static void ass_lazy_track_init(void)
+{
+	ass_track_t* track = frame_context.track;
+	if (track->PlayResX && track->PlayResY)
+		return;
+	if (!track->PlayResX && !track->PlayResY) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "Neither PlayResX nor PlayResY defined. Assuming 384x288.  \n");
+		track->PlayResX = 384;
+		track->PlayResY = 288;
+	} else {
+		double orig_aspect = (global_settings->aspect * frame_context.height) / frame_context.orig_height;
+		if (!track->PlayResY) {
+			track->PlayResY = track->PlayResX / orig_aspect + .5;
+			mp_msg(MSGT_GLOBAL, MSGL_WARN, "PlayResY undefined, setting %d  \n", track->PlayResY);
+		} else if (!track->PlayResX) {
+			track->PlayResX = track->PlayResY * orig_aspect + .5;
+			mp_msg(MSGT_GLOBAL, MSGL_WARN, "PlayResX undefined, setting %d  \n", track->PlayResX);
+		}
+	}
+}
+
+ass_instance_t* ass_init(void)
+{
+	char* family = 0;
+	char* path = 0;
+	char* fonts_path = 0;
+	int error;
+	fc_instance_t* fc_priv;
+	FT_Library ft;
+	ass_instance_t* priv;
+	
+	if (font_fontconfig && font_name)
+		family = strdup(font_name);
+	
+	if (!font_fontconfig && font_name)
+		path = strdup(font_name);
+	else
+		path = get_path("subfont.ttf");
+
+	fonts_path = get_path("fonts");
+	
+	fc_priv = fontconfig_init(fonts_path, family, path);
+
+	free(fonts_path);
+	if (path) free(path);
+	if (family) free(family);
+
+	if (!fc_priv)
+		return 0;
+	
+	error = FT_Init_FreeType( &ft );
+	if ( error ) { 
+		mp_msg(MSGT_GLOBAL, MSGL_FATAL, "FT_Init_FreeType failed\n");
+		fontconfig_done(fc_priv);
+		return 0;
+	}
+
+	priv = calloc(1, sizeof(ass_instance_t));
+	if (!priv) {
+		FT_Done_FreeType(ft);
+		fontconfig_done(fc_priv);
+		return 0;
+	}
+	priv->library = ft;
+	priv->fontconfig_priv = fc_priv;
+	// images_root and related stuff is zero-filled in calloc
+	
+	ass_face_cache_init();
+	ass_glyph_cache_init();
+
+	text_info.glyphs = calloc(MAX_GLYPHS, sizeof(glyph_info_t));
+	
+	return priv;
+}
+
+void ass_done(ass_instance_t* priv)
+{
+	ass_face_cache_done();
+	ass_glyph_cache_done();
+	if (priv && priv->library) FT_Done_FreeType(priv->library);
+	if (priv && priv->fontconfig_priv) fontconfig_done(priv->fontconfig_priv);
+	if (priv) free(priv);
+	if (text_info.glyphs) free(text_info.glyphs);
+}
+
+/**
+ * \brief Create a new ass_image_t and append it to images_root
+ * Parameters are the same as ass_image_t fields.
+ */
+static void my_draw_bitmap(unsigned char* bitmap, int bitmap_w, int bitmap_h, int stride, int dst_x, int dst_y, uint32_t color)
+{
+	ass_instance_t* priv = ass_instance;
+	ass_image_t* img;
+	
+	assert(priv->n_images <= priv->max_images);
+	if (priv->n_images == priv->max_images) {
+		if (!priv->max_images) priv->max_images = 100;
+		else priv->max_images *= 2;
+		priv->images_root = (ass_image_t*)realloc(priv->images_root, priv->max_images * sizeof(ass_image_t));
+	}
+	assert(priv->images_root);
+	img = priv->images_root + priv->n_images;
+
+	img->w = bitmap_w;
+	img->h = bitmap_h;
+	img->stride = stride;
+	img->bitmap = bitmap;
+	img->color = color;
+	img->dst_x = dst_x;
+	img->dst_y = dst_y;
+	
+	priv->n_images++;
+}
+
+/**
+ * \brief convert bitmap glyph into ass_image_t struct(s)
+ * \param bit freetype bitmap glyph, FT_PIXEL_MODE_GRAY
+ * \param dst_x bitmap x coordinate in video frame
+ * \param dst_y bitmap y coordinate in video frame
+ * \param color first color, RGBA
+ * \param color2 second color, RGBA
+ * \param brk x coordinate relative to glyph origin, color is used to the left of brk, color2 - to the right
+ * Performs clipping. Uses my_draw_bitmap for actual bitmap convertion.
+ */
+static int render_glyph(FT_BitmapGlyph bit, int dst_x, int dst_y, uint32_t color, uint32_t color2, int brk)
+{
+	// brk is relative to dst_x
+	// color = color left of brk
+	// color2 = color right of brk
+	int b_x0, b_y0, b_x1, b_y1; // visible part of the bitmap
+	int clip_x0, clip_y0, clip_x1, clip_y1;
+	int tmp;
+	FT_Bitmap* bitmap;
+
+	bitmap = &(bit->bitmap);
+	dst_x += bit->left;
+	dst_y -= bit->top;
+	brk -= bit->left;
+	
+	if (bitmap->pixel_mode != FT_PIXEL_MODE_GRAY) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "Unsupported pixel mode: %d\n", (int)(bitmap->pixel_mode));
+		return 1;
+	}
+
+	// clipping
+	clip_x0 = render_context.clip_x0;
+	clip_y0 = render_context.clip_y0;
+	clip_x1 = render_context.clip_x1;
+	clip_y1 = render_context.clip_y1;
+	b_x0 = 0;
+	b_y0 = 0;
+	b_x1 = bitmap->width;
+	b_y1 = bitmap->rows;
+	
+	tmp = dst_x - clip_x0;
+	if (tmp < 0) {
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip left\n");
+		b_x0 = - tmp;
+	}
+	tmp = dst_y - clip_y0;
+	if (tmp < 0) {
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip top\n");
+		b_y0 = - tmp;
+	}
+	tmp = clip_x1 - dst_x - bitmap->width;
+	if (tmp < 0) {
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip right\n");
+		b_x1 = bitmap->width + tmp;
+	}
+	tmp = clip_y1 - dst_y - bitmap->rows;
+	if (tmp < 0) {
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip bottom\n");
+		b_y1 = bitmap->rows + tmp;
+	}
+	
+	if ((b_y0 >= b_y1) || (b_x0 >= b_x1))
+		return 0;
+
+	if (brk > b_x0) { // draw left part
+		if (brk > b_x1) brk = b_x1;
+		my_draw_bitmap(bitmap->buffer + bitmap->pitch * b_y0 + b_x0, 
+			brk - b_x0, b_y1 - b_y0, bitmap->pitch,
+			dst_x + b_x0, dst_y + b_y0, color);
+	}
+	if (brk < b_x1) { // draw right part
+		if (brk < b_x0) brk = b_x0;
+		my_draw_bitmap(bitmap->buffer + bitmap->pitch * b_y0 + brk, 
+			b_x1 - brk, b_y1 - b_y0, bitmap->pitch,
+			dst_x + brk, dst_y + b_y0, color2);
+		
+	}
+	return 0;
+}
+
+/**
+ * \brief Render text_info_t struct into ass_images_t list
+ * Rasterize glyphs and put them in glyph cache.
+ */
+static int render_text(text_info_t* text_info, int dst_x, int dst_y)
+{
+	int pen_x, pen_y;
+	int error, error2;
+	int i;
+	FT_Glyph image;
+	FT_BitmapGlyph bit;
+	glyph_hash_val_t hash_val;
+
+	for (i = 0; i < text_info->length; ++i) {
+		if (text_info->glyphs[i].bitmap != 1) {
+			if ((text_info->glyphs[i].symbol == '\n') || (text_info->glyphs[i].symbol == 0))
+				continue;
+			error = FT_Glyph_To_Bitmap( &(text_info->glyphs[i].outline_glyph), FT_RENDER_MODE_NORMAL, 0, 1);
+			error2 = FT_Glyph_To_Bitmap( &(text_info->glyphs[i].glyph), FT_RENDER_MODE_NORMAL, 0, 1);
+
+			if (error || error2) {
+				FT_Done_Glyph(text_info->glyphs[i].outline_glyph);
+				FT_Done_Glyph(text_info->glyphs[i].glyph);
+				mp_msg(MSGT_GLOBAL, MSGL_WARN, "FT_Glyph_To_Bitmap error %d %d, symbol %d, index %d\n", 
+						error, error2, text_info->glyphs[i].symbol, text_info->glyphs[i].hash_key.index);
+				text_info->glyphs[i].symbol = 0; // do not render
+				continue;
+			}
+			// cache
+			text_info->glyphs[i].hash_key.bitmap = 1; // other hash_key fields were set in get_glyph()
+			hash_val.bbox_scaled = text_info->glyphs[i].bbox;
+			hash_val.outline_glyph = text_info->glyphs[i].outline_glyph;
+			hash_val.glyph = text_info->glyphs[i].glyph;
+			hash_val.advance.x = text_info->glyphs[i].advance.x;
+			hash_val.advance.y = text_info->glyphs[i].advance.y;
+			cache_add_glyph(&(text_info->glyphs[i].hash_key), &hash_val);
+		}
+	}
+
+	for (i = 0; i < text_info->length; ++i) {
+		glyph_info_t* info = text_info->glyphs + i;
+		if ((info->symbol == 0) || (info->symbol == '\n'))
+			continue;
+
+		pen_x = dst_x + info->pos.x;
+		pen_y = dst_y + info->pos.y;
+		image = info->outline_glyph;
+		bit = (FT_BitmapGlyph)image;
+		
+		if ((info->effect_type == EF_KARAOKE_KO) && (info->effect_timing <= info->bbox.xMax)) {
+			// do nothing
+		} else
+			render_glyph(bit, pen_x, pen_y, info->c3, 0, 1000000);
+	}
+	for (i = 0; i < text_info->length; ++i) {
+		glyph_info_t* info = text_info->glyphs + i;
+		if ((info->symbol == 0) || (info->symbol == '\n'))
+			continue;
+
+		pen_x = dst_x + info->pos.x;
+		pen_y = dst_y + info->pos.y;
+		image = info->glyph;
+		bit = (FT_BitmapGlyph)image;
+
+		if ((info->effect_type == EF_KARAOKE) || (info->effect_type == EF_KARAOKE_KO)) {
+			if (info->effect_timing > info->bbox.xMax)
+				render_glyph(bit, pen_x, pen_y, info->c1, 0, 1000000);
+			else
+				render_glyph(bit, pen_x, pen_y, info->c2, 0, 1000000);
+		} else if (info->effect_type == EF_KARAOKE_KF) {
+			render_glyph(bit, pen_x, pen_y, info->c1, info->c2, info->effect_timing);
+		} else
+			render_glyph(bit, pen_x, pen_y, info->c1, 0, 1000000);
+	}
+
+	return 0;
+}
+
+/**
+ * \brief Mapping between script and screen coordinates
+ */
+static int x2scr(int x) {
+	return x*frame_context.width / frame_context.track->PlayResX;
+}
+/**
+ * \brief Mapping between script and screen coordinates
+ */
+static int y2scr(int y) {
+	return y * frame_context.orig_height / frame_context.track->PlayResY + global_settings->top_margin;
+}
+// the same for toptitles
+static int y2scr_top(int y) {
+	return y * frame_context.orig_height / frame_context.track->PlayResY;
+}
+// the same for subtitles
+static int y2scr_sub(int y) {
+	return y * frame_context.orig_height / frame_context.track->PlayResY + global_settings->top_margin + global_settings->bottom_margin;
+}
+
+static void vmirror_bbox(FT_BBox* orig, FT_BBox* pbbox) {
+	pbbox->xMin = orig->xMin;
+	pbbox->xMax = orig->xMax;
+	pbbox->yMin = - orig->yMax;
+	pbbox->yMax = - orig->yMin;
+}
+
+static void compute_string_bbox( text_info_t* info, FT_BBox *abbox ) {
+	FT_BBox bbox;
+	int n;
+	
+	/* initialize string bbox to "empty" values */
+	bbox.xMin = bbox.yMin = 32000;
+	bbox.xMax = bbox.yMax = -32000;
+	
+	/* for each glyph image, compute its bounding box, */
+	/* translate it, and grow the string bbox */
+	for ( n = 0; n < info->length; n++ ) {
+		FT_BBox glyph_bbox;
+		vmirror_bbox( &(info->glyphs[n].bbox), &glyph_bbox );
+		glyph_bbox.xMin += info->glyphs[n].pos.x;
+		glyph_bbox.xMax += info->glyphs[n].pos.x;
+		glyph_bbox.yMin += info->glyphs[n].pos.y;
+		glyph_bbox.yMax += info->glyphs[n].pos.y;
+		if ( glyph_bbox.xMin < bbox.xMin ) bbox.xMin = glyph_bbox.xMin;
+		if ( glyph_bbox.yMin < bbox.yMin ) bbox.yMin = glyph_bbox.yMin;
+		if ( glyph_bbox.xMax > bbox.xMax ) bbox.xMax = glyph_bbox.xMax;
+		if ( glyph_bbox.yMax > bbox.yMax ) bbox.yMax = glyph_bbox.yMax;
+	}
+	
+	/* check that we really grew the string bbox */
+	if ( bbox.xMin > bbox.xMax ) {
+		bbox.xMin = 0;
+		bbox.yMin = 0;
+		bbox.xMax = 0;
+		bbox.yMax = 0;
+	}
+
+	/* return string bbox */
+	*abbox = bbox;
+}
+
+
+/**
+ * \brief Check if starting part of (*p) matches sample. If true, shift p to the first symbol after the matching part.
+ */
+static inline int mystrcmp(char** p, char* sample) {
+	int len = strlen(sample);
+	if (strncmp(*p, sample, len) == 0) {
+		(*p) += len;
+		return 1;
+	} else
+		return 0;
+}
+
+static void change_font_size(int sz)
+{
+	double size = (double)sz * global_settings->font_size_coeff * 0.8;
+	size *= frame_context.height;
+	size /= frame_context.track->PlayResY;
+
+	if (size < 1)
+		size = 1;
+	else if (size > frame_context.height * 2)
+		size = frame_context.height * 2;
+	
+	FT_Set_Pixel_Sizes(render_context.face, 0, size);
+
+	render_context.font_size = sz;
+}
+
+/**
+ * \brief Change current font, using setting from render_context.
+ */
+static void update_font(void)
+{
+	int error;
+	unsigned val;
+	ass_instance_t* priv = frame_context.ass_priv;
+	face_desc_t desc;
+	desc.family = strdup(render_context.family);
+
+	val = render_context.bold;
+	// 0 = normal, 1 = bold, >1 = exact weight
+	if (val == 0) val = 80; // normal
+	else if (val == 1) val = 200; // bold
+	desc.bold = val;
+
+	val = render_context.italic;
+	if (val == 0) val = 0; // normal
+	else if (val == 1) val = 110; //italic
+	desc.italic = val;
+
+	error = ass_new_face(priv->library, priv->fontconfig_priv, &desc, &(render_context.face));
+	if (error) {
+		render_context.face = 0;
+	}
+	
+	if (render_context.face)
+	{
+		change_font_size(render_context.font_size);
+	}
+}
+
+/**
+ * \brief Change border width
+ */
+static void change_border(double border)
+{
+	if (!render_context.stroker) {
+		if (!no_more_font_messages)
+			mp_msg(MSGT_GLOBAL, MSGL_WARN, "No stroker!\n");
+	} else {
+		render_context.border = border;
+		FT_Stroker_Set( render_context.stroker,
+				(int)(64 * border),
+				FT_STROKER_LINECAP_ROUND,
+				FT_STROKER_LINEJOIN_ROUND,
+				0 );
+	}
+}
+
+#define _r(c)  ((c)>>24)
+#define _g(c)  (((c)>>16)&0xFF)
+#define _b(c)  (((c)>>8)&0xFF)
+#define _a(c)  ((c)&0xFF)
+
+/**
+ * \brief Calculate a weighted average of two colors
+ * calculates c1*(1-a) + c2*a, but separately for each component except alpha
+ */
+static void change_color(uint32_t* var, uint32_t new, double pwr)
+{
+	(*var)= ((uint32_t)(_r(*var) * (1 - pwr) + _r(new) * pwr) << 24) +
+		((uint32_t)(_g(*var) * (1 - pwr) + _g(new) * pwr) << 16) +
+		((uint32_t)(_b(*var) * (1 - pwr) + _b(new) * pwr) << 8) +
+		_a(*var);
+}
+
+// like change_color, but for alpha component only
+static void change_alpha(uint32_t* var, uint32_t new, double pwr)
+{
+	*var = (_r(*var) << 24) + (_g(*var) << 16) + (_b(*var) << 8) + (_a(*var) * (1 - pwr) + _a(new) * pwr);
+}
+
+
+/**
+ * \brief Calculate alpha value by piecewise linear function
+ * Used for \fad, \fade implementation.
+ */
+static void interpolate_alpha(long long now, 
+		long long t1, long long t2, long long t3, long long t4,
+		unsigned a1, unsigned a2, unsigned a3)
+{
+	unsigned a;
+	double cf;
+	if (now <= t1) {
+		a = a1;
+	} else if (now >= t4) {
+		a = a3;
+	} else if (now < t2) { // and > t1
+		cf = ((double)(now - t1)) / (t2 - t1);
+		a = a1 * (1 - cf) + a2 * cf;
+	} else if (now > t3) {
+		cf = ((double)(now - t3)) / (t4 - t3);
+		a = a2 * (1 - cf) + a3 * cf;
+	} else { // t2 <= now <= t3
+		a = a2;
+	}
+
+
+	change_alpha(&render_context.c1, a, 1.);
+	change_alpha(&render_context.c2, a, 1.);
+	change_alpha(&render_context.c3, a, 1.);
+	change_alpha(&render_context.c4, a, 1.);
+}
+
+/**
+ * \brief Parse style override tag.
+ * \param p string to parse
+ * \param pwr multiplier for some tag effects (comes from \t tags)
+ */
+static char* parse_tag(char* p, double pwr) {
+#define skip_all(x) if (*p == (x)) ++p; else { \
+	while ((*p != (x)) && (*p != '}') && (*p != 0)) {++p;} }
+#define skip(x) if (*p == (x)) ++p; else { return p; }
+	
+	skip_all('\\');
+	if ((*p == '}') || (*p == 0))
+		return p;
+
+	if (mystrcmp(&p, "fsc")) {
+		char tp = *p++;
+		double val;
+		if (tp == 'x') {
+			if (mystrtod(&p, &val)) {
+				val /= 100;
+				render_context.scale_x = (val - 1.) * pwr + 1.;
+			} else
+				render_context.scale_x = render_context.style->ScaleX;
+		} else if (tp == 'y') {
+			if (mystrtod(&p, &val)) {
+				val /= 100;
+				render_context.scale_y = (val - 1.) * pwr + 1.;
+			} else
+				render_context.scale_y = render_context.style->ScaleY;
+		}
+	} else if (mystrcmp(&p, "fsp")) {
+		int val;
+		if (mystrtoi(&p, 10, &val))
+			render_context.hspacing = val * pwr;
+		else
+			render_context.hspacing = 0;
+	} else if (mystrcmp(&p, "fs")) {
+		int val;
+		if (mystrtoi(&p, 10, &val))
+			val = render_context.font_size * ( 1 - pwr ) + val * pwr;
+		else
+			val = render_context.style->FontSize;
+		if (render_context.face)
+			change_font_size(val);
+	} else if (mystrcmp(&p, "bord")) {
+		double val;
+		if (mystrtod(&p, &val))
+			val = render_context.border * ( 1 - pwr ) + val * pwr;
+		else
+			val = (render_context.style->BorderStyle == 1) ? render_context.style->Outline : 1.;
+		change_border(val);
+	} else if (mystrcmp(&p, "move")) {
+		int x1, x2, y1, y2;
+		long long t1, delta_t, t;
+		int x, y;
+		double k;
+		skip('(');
+		x1 = strtol(p, &p, 10);
+		skip(',');
+		y1 = strtol(p, &p, 10);
+		skip(',');
+		x2 = strtol(p, &p, 10);
+		skip(',');
+		y2 = strtol(p, &p, 10);
+		skip(')'); // FIXME: 2 more optional args
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "movement: (%d, %d) -> (%d, %d)\n", x1, y1, x2, y2);
+		t1 = render_context.event->Start;
+		delta_t = render_context.event->Duration;
+		t = frame_context.time; // FIXME: move to render_context
+		k = ((double)(t - t1)) / delta_t;
+		x = k * (x2 - x1) + x1;
+		y = k * (y2 - y1) + y1;
+		render_context.pos_x = x;
+		render_context.pos_y = y;
+		render_context.detect_collisions = 0;
+		render_context.evt_type = EVENT_POSITIONED;
+	} else if (mystrcmp(&p, "frx") || mystrcmp(&p, "fry")) {
+		int val;
+		mystrtoi(&p, 10, &val);
+		mp_msg(MSGT_GLOBAL, MSGL_V, "frx/fry unimplemented \n");
+	} else if (mystrcmp(&p, "frz") || mystrcmp(&p, "fr")) {
+		double angle;
+		int val;
+		val = strtol(p, &p, 10);
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "setting rotation to %.2f\n", val * pwr);
+		angle = M_PI * val / 180;
+		render_context.rotation = angle * pwr;
+	} else if (mystrcmp(&p, "fn")) {
+		char* start = p;
+		char* family;
+		skip_all('\\');
+		family = malloc(p - start + 1);
+		strncpy(family, start, p - start);
+		family[p - start] = '\0';
+		if (render_context.family)
+			free(render_context.family);
+		render_context.family = family;
+		update_font();
+	} else if (mystrcmp(&p, "alpha")) {
+		uint32_t val;
+		if (strtocolor(&p, &val)) {
+			unsigned char a = val >> 24;
+			change_alpha(&render_context.c1, a, pwr);
+			change_alpha(&render_context.c2, a, pwr);
+			change_alpha(&render_context.c3, a, pwr);
+			change_alpha(&render_context.c4, a, pwr);
+		} else {
+			change_alpha(&render_context.c1, render_context.style->PrimaryColour, pwr);
+			change_alpha(&render_context.c2, render_context.style->SecondaryColour, pwr);
+			change_alpha(&render_context.c3, render_context.style->OutlineColour, pwr);
+			change_alpha(&render_context.c4, render_context.style->BackColour, pwr);
+		}
+		// FIXME: simplify
+	} else if (mystrcmp(&p, "an")) {
+		int val = strtol(p, &p, 10);
+		int v = (val - 1) / 3; // 0, 1 or 2 for vertical alignment
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "an %d\n", val);
+		if (v != 0) v = 3 - v;
+		val = ((val - 1) % 3) + 1; // horizontal alignment
+		val += v*4;
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "align %d\n", val);
+		render_context.alignment = val;
+	} else if (mystrcmp(&p, "a")) {
+		int val = strtol(p, &p, 10);
+		render_context.alignment = val;
+	} else if (mystrcmp(&p, "pos")) {
+		int v1, v2;
+		skip('(');
+		v1 = strtol(p, &p, 10);
+		skip(',');
+		v2 = strtol(p, &p, 10);
+		skip(')');
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "pos(%d, %d)\n", v1, v2);
+		render_context.evt_type = EVENT_POSITIONED;
+		render_context.detect_collisions = 0;
+		render_context.pos_x = v1;
+		render_context.pos_y = v2;
+	} else if (mystrcmp(&p, "fade")) {
+		int a1, a2, a3, v1, v2, v3, v4;
+		skip('(');
+		a1 = strtol(p, &p, 10);
+		skip(',');
+		a2 = strtol(p, &p, 10);
+		skip(',');
+		a3 = strtol(p, &p, 10);
+		skip(',');
+		v1 = strtol(p, &p, 10);
+		skip(',');
+		v2 = strtol(p, &p, 10);
+		skip(',');
+		v3 = strtol(p, &p, 10);
+		skip(',');
+		v4 = strtol(p, &p, 10);
+		skip(')');
+		interpolate_alpha(frame_context.time - render_context.event->Start, v1, v2, v3, v4, a1, a2, a3);
+	} else if (mystrcmp(&p, "fad")) {
+		int v1, v2;
+		long long now, t1, t2, t3, t4;
+		skip('(');
+		v1 = strtol(p, &p, 10);
+		skip(',');
+		v2 = strtol(p, &p, 10);
+		skip(')');
+		now = frame_context.time;
+		t1 = render_context.event->Start;
+		t2 = t1 + v1;
+		t4 = render_context.event->Start + render_context.event->Duration;
+		t3 = t4 - v2;
+		interpolate_alpha(now, t1, t2, t3, t4, 0xFF, 0, 0xFF);
+	} else if (mystrcmp(&p, "org")) {
+		int v1, v2;
+		skip('(');
+		v1 = strtol(p, &p, 10);
+		skip(',');
+		v2 = strtol(p, &p, 10);
+		skip(')');
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "org(%d, %d)\n", v1, v2);
+		//				render_context.evt_type = EVENT_POSITIONED;
+		render_context.org_x = v1;
+		render_context.org_y = v2;
+	} else if (mystrcmp(&p, "t")) {
+		double v[3];
+		int v1, v2;
+		double v3;
+		int cnt;
+		long long t1, t2, t, delta_t;
+		double k;
+		skip('(');
+		for (cnt = 0; cnt < 3; ++cnt) {
+			if (*p == '\\')
+				break;
+			v[cnt] = strtod(p, &p);
+			skip(',');
+		}
+		if (cnt == 3) {
+			v1 = v[0]; v2 = v[1]; v3 = v[2];
+		} else if (cnt == 2) {
+			v1 = v[0]; v2 = v[1]; v3 = 1.;
+		} else if (cnt == 1) {
+			v1 = 0; v2 = render_context.event->Duration; v3 = v[0];
+		} else { // cnt == 0
+			v1 = 0; v2 = render_context.event->Duration; v3 = 1.;
+		}
+		render_context.detect_collisions = 0;
+		t1 = v1;
+		t2 = v2;
+		delta_t = v2 - v1;
+		t = frame_context.time - render_context.event->Start; // FIXME: move to render_context
+		if (t < t1)
+			k = 0.;
+		else if (t > t2)
+			k = 1.;
+		else k = ((double)(t - t1)) / delta_t;
+		while (*p == '\\')
+			p = parse_tag(p, k); // maybe k*pwr ? no, specs forbid nested \t's 
+		skip_all(')'); // FIXME: better skip(')'), but much more tags support required
+	} else if (mystrcmp(&p, "clip")) {
+		int x0, y0, x1, y1;
+		int res = 1;
+		skip('(');
+		res &= mystrtoi(&p, 10, &x0);
+		skip(',');
+		res &= mystrtoi(&p, 10, &y0);
+		skip(',');
+		res &= mystrtoi(&p, 10, &x1);
+		skip(',');
+		res &= mystrtoi(&p, 10, &y1);
+		skip(')');
+		if (res) {
+			render_context.clip_x0 = render_context.clip_x0 * (1-pwr) + x0 * pwr;
+			render_context.clip_x1 = render_context.clip_x1 * (1-pwr) + x1 * pwr;
+			render_context.clip_y0 = render_context.clip_y0 * (1-pwr) + y0 * pwr;
+			render_context.clip_y1 = render_context.clip_y1 * (1-pwr) + y1 * pwr;
+		} else {
+			render_context.clip_x0 = 0;
+			render_context.clip_y0 = 0;
+			render_context.clip_x1 = frame_context.track->PlayResX;
+			render_context.clip_y1 = frame_context.track->PlayResY;
+		}
+	} else if (mystrcmp(&p, "c")) {
+		uint32_t val;
+		if (!strtocolor(&p, &val))
+			val = render_context.style->PrimaryColour;
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "color: %X\n", val);
+		change_color(&render_context.c1, val, pwr);
+	} else if ((*p >= '1') && (*p <= '4') && (++p) && (mystrcmp(&p, "c") || mystrcmp(&p, "a"))) {
+		char n = *(p-2);
+		char cmd = *(p-1);
+		uint32_t* pcolor;
+		uint32_t val;
+		assert((n >= '1') && (n <= '4'));
+		if (!strtocolor(&p, &val))
+			switch(n) {
+				case '1': val = render_context.style->PrimaryColour; break;
+				case '2': val = render_context.style->SecondaryColour; break;
+				case '3': val = render_context.style->OutlineColour; break;
+				case '4': val = render_context.style->BackColour; break;
+				default : val = 0; break; // impossible due to assert; avoid compilation warning
+			}
+		switch (n) {
+			case '1': pcolor = &render_context.c1; break;
+			case '2': pcolor = &render_context.c2; break;
+			case '3': pcolor = &render_context.c3; break;
+			case '4': pcolor = &render_context.c4; break;
+			default : pcolor = 0; break;
+		}
+		switch (cmd) {
+			case 'c': change_color(pcolor, val, pwr); break;
+			case 'a': change_alpha(pcolor, val >> 24, pwr); break;
+			default: mp_msg(MSGT_GLOBAL, MSGL_WARN, "Bad command: %c%c\n", n, cmd); break;
+		}
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "single c/a at %f: %c%c = %X   \n", pwr, n, cmd, *pcolor);
+	} else if (mystrcmp(&p, "r")) {
+		render_context.c1 = render_context.style->PrimaryColour;
+		render_context.c2 = render_context.style->SecondaryColour;
+		render_context.c3 = render_context.style->OutlineColour;
+		render_context.c4 = render_context.style->BackColour;
+		render_context.font_size = render_context.style->FontSize;
+
+		if (render_context.family)
+			free(render_context.family);
+		render_context.family = strdup(render_context.style->FontName);
+		render_context.bold = - render_context.style->Bold;
+		render_context.italic = - render_context.style->Italic;
+		update_font();
+
+		if (render_context.stroker) {
+			double border = (render_context.style->BorderStyle == 1) ? render_context.style->Outline : 1.;
+			change_border(border);
+		}
+		render_context.scale_x = render_context.style->ScaleX;
+		render_context.scale_y = render_context.style->ScaleY;
+		render_context.hspacing = 0; // FIXME
+		
+		// FIXME: does not reset unsupported attributes.
+	} else if (mystrcmp(&p, "be")) {
+		int val;
+		mystrtoi(&p, 10, &val);
+		mp_msg(MSGT_GLOBAL, MSGL_V, "be unimplemented \n");
+	} else if (mystrcmp(&p, "b")) {
+		int b;
+		if (mystrtoi(&p, 10, &b))
+			render_context.bold = b;
+		else
+			render_context.bold = - render_context.style->Bold;
+		update_font();
+	} else if (mystrcmp(&p, "i")) {
+		int i;
+		if (mystrtoi(&p, 10, &i))
+			render_context.italic = i;
+		else
+			render_context.italic = - render_context.style->Italic;
+		update_font();
+	} else if (mystrcmp(&p, "kf") || mystrcmp(&p, "K")) {
+		int val = strtol(p, &p, 10);
+		render_context.effect_type = EF_KARAOKE_KF;
+		render_context.effect_timing = val * 10;
+	} else if (mystrcmp(&p, "ko")) {
+		int val = strtol(p, &p, 10);
+		render_context.effect_type = EF_KARAOKE_KO;
+		render_context.effect_timing = val * 10;
+	} else if (mystrcmp(&p, "k")) {
+		int val = strtol(p, &p, 10);
+		render_context.effect_type = EF_KARAOKE;
+		render_context.effect_timing = val * 10;
+	}
+
+	return p;
+
+#undef skip
+#undef skip_all
+}
+
+/**
+ * \brief Get next ucs4 char from string, parsing and executing style overrides
+ * \param str string pointer
+ * \return ucs4 code of the next char
+ * On return str points to the unparsed part of the string
+ */
+static unsigned get_next_char(char** str)
+{
+	char* p = *str;
+	unsigned chr;
+	if (*p == '{') { // '\0' goes here
+		p++;
+		while (1) {
+			p = parse_tag(p, 1.);
+			if (*p == '}') { // end of tag
+				p++;
+				if (*p == '{') {
+					p++;
+					continue;
+				} else
+					break;
+			} else if (*p != '\\')
+				mp_msg(MSGT_GLOBAL, MSGL_V, "Unable to parse: \"%s\" \n", p);
+			if (*p == 0)
+				break;
+		}
+	}
+	if (*p == '\t') {
+		++p;
+		*str = p;
+		return ' ';
+	}
+	if (*p == '\\') {
+		if ((*(p+1) == 'N') || ((*(p+1) == 'n') && (frame_context.track->WrapStyle == 2))) {
+			p += 2;
+			*str = p;
+			return '\n';
+		} else if (*(p+1) == 'n') {
+			p += 2;
+			*str = p;
+			return ' ';
+		}
+	}
+	chr = utf8_get_char(&p);
+	*str = p;
+	return chr;
+}
+
+/**
+ * \brief Start new event. Reset render_context.
+ */
+static int init_render_context(ass_event_t* event)
+{
+	int error;
+
+// init render_context
+	render_context.event = event;
+	render_context.style = frame_context.track->styles + event->Style;
+	
+	render_context.font_size = render_context.style->FontSize;
+	render_context.evt_type = EVENT_NORMAL;
+	render_context.alignment = 0;
+	render_context.rotation = 0.;
+	render_context.pos_x = 0;
+	render_context.pos_y = 0;
+	render_context.org_x = 0;
+	render_context.org_y = 0;
+	render_context.scale_x = render_context.style->ScaleX;
+	render_context.scale_y = render_context.style->ScaleY;
+	render_context.hspacing = 0;
+	render_context.c1 = render_context.style->PrimaryColour;
+	render_context.c2 = render_context.style->SecondaryColour;
+	render_context.c3 = render_context.style->OutlineColour;
+	render_context.c4 = render_context.style->BackColour;
+	render_context.clip_x0 = 0;
+	render_context.clip_y0 = 0;
+	render_context.clip_x1 = frame_context.track->PlayResX;
+	render_context.clip_y1 = frame_context.track->PlayResY;
+	render_context.detect_collisions = 1;
+	
+	if (render_context.family)
+		free(render_context.family);
+	render_context.family = strdup(render_context.style->FontName);
+	render_context.bold = - render_context.style->Bold; // style value for bold text is -1
+	render_context.italic = - render_context.style->Italic;
+	
+	update_font();
+
+	if (render_context.face) {
+#if (FREETYPE_MAJOR > 2) || ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR > 1))
+		error = FT_Stroker_New( ass_instance->library, &render_context.stroker );
+#else // < 2.2
+		error = FT_Stroker_New( render_context.face->memory, &render_context.stroker );
+#endif
+		if ( error ) {
+			mp_msg(MSGT_GLOBAL, MSGL_V, "failed to get stroker\n");
+			render_context.stroker = 0;
+		} else {
+			// FIXME: probably wrong when render_context.Border == 3
+			double border = (render_context.style->BorderStyle == 1) ? render_context.style->Outline : 1.;
+			change_border(border);
+		}
+	}
+	
+	return 0;
+}
+
+static int free_render_context(void)
+{
+	if (render_context.stroker != 0) {
+		FT_Stroker_Done(render_context.stroker);
+		render_context.stroker = 0;
+	}
+	return 0;
+}
+
+/**
+ * \brief Get normal and outline glyphs from cache (if possible) or font face
+ * \param index face glyph index
+ * \param symbol ucs4 char
+ * \param info out: struct filled with extracted data
+ * \param advance advance vector of the extracted glyph
+ * \return 0 on success
+ */
+static int get_glyph(int index, int symbol, glyph_info_t* info, FT_Vector* advance)
+{
+	int error;
+	glyph_hash_val_t* val;
+	glyph_hash_key_t* key = &(info->hash_key);
+	
+	key->face = render_context.face;
+	key->size = render_context.font_size;
+	key->index = index;
+	key->outline = (render_context.border * 0xFFFF); // convert to 16.16
+	key->scale_x = (render_context.scale_x * 0xFFFF);
+	key->scale_y = (render_context.scale_y * 0xFFFF);
+	key->angle = (render_context.rotation * 0xFFFF);
+	key->advance = *advance;
+	key->bold = render_context.bold;
+	key->italic = render_context.italic;
+
+	key->bitmap = 1; // looking for bitmap glyph
+
+	
+	val = cache_find_glyph(key);
+//	val = 0;
+	
+	if (val) {
+		// bitmap glyph found, no need for FT_Glyph_Copy
+		info->glyph = val->glyph;
+		info->outline_glyph = val->outline_glyph;
+		info->bbox = val->bbox_scaled;
+		info->advance.x = val->advance.x;
+		info->advance.y = val->advance.y;
+		info->bitmap = 1; // bitmap glyph
+
+		return 0;
+	}
+
+	// not found, get a new outline glyph from face
+//	mp_msg(MSGT_GLOBAL, MSGL_INFO, "miss, index = %d, symbol = %c, adv = (%d, %d)\n", index, symbol, advance->x, advance->y);
+	
+	error = FT_Load_Glyph(render_context.face, index, FT_LOAD_NO_BITMAP );
+	if (error) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "Error loading glyph\n");
+		return error;
+	}
+	
+#if (FREETYPE_MAJOR > 2) || \
+    ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR >= 2)) || \
+    ((FREETYPE_MAJOR == 2) && (FREETYPE_MINOR == 1) && (FREETYPE_PATCH >= 10))
+// FreeType >= 2.1.10 required
+	if (!(render_context.face->style_flags & FT_STYLE_FLAG_ITALIC) && 
+			((render_context.italic == 1) || (render_context.italic > 55))) {
+		FT_GlyphSlot_Oblique(render_context.face->glyph);
+	}
+#endif
+	error = FT_Get_Glyph(render_context.face->glyph, &(info->glyph));
+	if (error) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "Error getting glyph\n");
+		return error;
+	}
+
+	info->advance.x = info->glyph->advance.x >> 10;
+	info->advance.y = info->glyph->advance.y >> 10;
+
+	info->outline_glyph = info->glyph;
+	FT_Glyph_Stroke( &(info->outline_glyph), render_context.stroker, 0 ); // don't destroy original
+
+	info->bitmap = 0; // outline glyph
+
+	return 0;
+}
+
+/**
+ * \brief rearrange text between lines
+ * \param max_text_width maximal text line width in pixels
+ * The algo is similar to the one in libvo/sub.c:
+ * 1. Place text, wrapping it when current line is full
+ * 2. Try moving words from the end of a line to the beginning of the next one while it reduces
+ * the difference in lengths between this two lines.
+ * The result may not be optimal, but usually is good enough.
+ */
+static void wrap_lines_smart(int max_text_width)
+{
+	int i, j;
+	glyph_info_t *cur, *s1, *e1, *s2, *s3, *w;
+	int last_space;
+	int break_type;
+	int exit;
+	int pen_shift_x;
+	int pen_shift_y;
+	int max_asc, max_desc;
+	int cur_line;
+
+	last_space = -1;
+	text_info.n_lines = 1;
+	break_type = 0;
+	s1 = text_info.glyphs; // current line start
+	for (i = 0; i < text_info.length; ++i) {
+		cur = text_info.glyphs + i;
+		int break_at = -1;
+		int s_offset = s1->bbox.xMin + s1->pos.x;
+		int len = (cur->bbox.xMax + cur->pos.x) - s_offset;
+
+		if (cur->symbol == '\n') {
+			break_type = 2;
+			break_at = i;
+			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "forced line break at %d\n", break_at);
+		}
+		
+		if (len >= max_text_width) {
+			break_type = 1;
+			break_at = last_space;
+			if (break_at == -1)
+				break_at = i - 1;
+			if (break_at == -1)
+				break_at = 0;
+			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "overfill at %d\n", i);
+			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "line break at %d\n", break_at);
+		}
+
+		if (break_at != -1) {
+			// need to use one more line
+			// marking break_at+1 as start of a new line
+			int lead = break_at + 1; // the first symbol of the new line
+			if (text_info.n_lines >= MAX_LINES) {
+				// to many lines ! 
+				// no more linebreaks
+				for (j = lead; j < text_info.length; ++j)
+					text_info.glyphs[j].linebreak = 0;
+				break;
+			}
+			if (lead < text_info.length)
+				text_info.glyphs[lead].linebreak = break_type;
+			last_space = -1;
+			s1 = text_info.glyphs + lead;
+			s_offset = s1->bbox.xMin + s1->pos.x;
+			text_info.n_lines ++;
+		}
+		
+		if (cur->symbol == ' ')
+			last_space = i;
+	}
+#define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y))
+	exit = 0;
+	while (!exit) {
+		exit = 1;
+		w = s3 = text_info.glyphs;
+		s1 = s2 = 0;
+		for (i = 0; i <= text_info.length; ++i) {
+			cur = text_info.glyphs + i;
+			if ((i == text_info.length) || cur->linebreak) {
+				s1 = s2;
+				s2 = s3;
+				s3 = cur;
+//				printf("line: %d, %d, %d  \n", s1 - text_info.glyphs, s2 - text_info.glyphs, s3 - text_info.glyphs);
+				if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft'
+					int l1, l2, l1_new, l2_new;
+
+					w = s2;
+					do { --w; } while ((w > s1) && (w->symbol == ' '));
+					do { --w; } while ((w > s1) && (w->symbol != ' '));
+					e1 = w;
+					do { --e1; } while ((e1 > s1) && (e1->symbol == ' '));
+					if (w->symbol == ' ') ++w;
+
+//					printf("check: %d, %d, %d, w: %d, e: %d  \n", s1 - text_info.glyphs, s2 - text_info.glyphs, s3 - text_info.glyphs,
+//							w - text_info.glyphs, e1 - text_info.glyphs);
+
+					l1 = ((s2-1)->bbox.xMax + (s2-1)->pos.x) - (s1->bbox.xMin + s1->pos.x);
+					l2 = ((s3-1)->bbox.xMax + (s3-1)->pos.x) - (s2->bbox.xMin + s2->pos.x);
+					l1_new = (e1->bbox.xMax + e1->pos.x) - (s1->bbox.xMin + s1->pos.x);
+					l2_new = ((s3-1)->bbox.xMax + (s3-1)->pos.x) - (w->bbox.xMin + w->pos.x);
+
+					if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) {
+						w->linebreak = 1;
+						s2->linebreak = 0;
+						exit = 0;
+					}
+				}
+			}
+			if (i == text_info.length)
+				break;
+		}
+		
+	}
+	assert(text_info.n_lines >= 1);
+#undef DIFF
+	
+	text_info.height = 0;
+	max_asc = max_desc = 0;
+	cur_line = 0;
+	for (i = 0; i < text_info.length + 1; ++i) {
+		if ((i == text_info.length) || text_info.glyphs[i].linebreak) {
+			text_info.lines[cur_line].asc = max_asc;
+			text_info.lines[cur_line].desc = max_desc;
+			text_info.height += max_asc + max_desc;
+			cur_line ++;
+			max_asc = max_desc = 0;
+		}
+		if (i < text_info.length) {
+			cur = text_info.glyphs + i;
+			if (cur->asc > max_asc)
+				max_asc = cur->asc * render_context.scale_y;
+			if (cur->desc > max_desc)
+				max_desc = cur->desc * render_context.scale_y;
+		}
+	}
+	
+	pen_shift_x = 0;
+	pen_shift_y = 0;
+	cur_line = 1;
+	for (i = 0; i < text_info.length; ++i) {
+		cur = text_info.glyphs + i;
+		if (cur->linebreak) {
+			int height = text_info.lines[cur_line - 1].desc + text_info.lines[cur_line].asc;
+			cur_line ++;
+			pen_shift_x = - cur->pos.x;
+			pen_shift_y += (height >> 6) + global_settings->line_spacing;
+			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "shifting from %d to %d by (%d, %d)\n", i, text_info.length - 1, pen_shift_x, pen_shift_y);
+		}
+		cur->pos.x += pen_shift_x;
+		cur->pos.y += pen_shift_y;
+	}
+//	printf("=============  \n");
+}
+
+/**
+ * \brief determine karaoke effects
+ * Karaoke effects cannot be calculated during parse stage (get_next_char()),
+ * so they are done in a separate step.
+ * Parse stage: when karaoke style override is found, its parameters are stored in the next glyph's 
+ * (the first glyph of the karaoke word)'s effect_type and effect_timing.
+ * This function:
+ * 1. sets effect_type for all glyphs in the word (_karaoke_ word)
+ * 2. sets effect_timing for all glyphs to x coordinate of the border line between the left and right karaoke parts
+ * (left part is filled with PrimaryColour, right one - with SecondaryColour).
+ */
+static void process_karaoke_effects(void)
+{
+	glyph_info_t *cur, *cur2;
+	glyph_info_t *s1, *e1; // start and end of the current word
+	glyph_info_t *s2; // start of the next word
+	int i;
+	int timing; // current timing
+	int tm_start, tm_end; // timings at start and end of the current word
+	int tm_current;
+	double dt;
+	int x;
+	int x_start, x_end;
+
+	tm_current = frame_context.time - render_context.event->Start;
+	timing = 0;
+	s1 = s2 = 0;
+	for (i = 0; i <= text_info.length; ++i) {
+		cur = text_info.glyphs + i;
+		if ((i == text_info.length) || (cur->effect_type != EF_NONE)) {
+			s1 = s2;
+			s2 = cur;
+			if (s1) {
+				e1 = s2 - 1;
+				tm_start = timing;
+				tm_end = timing + s1->effect_timing;
+				timing = tm_end;
+				x_start = s1->bbox.xMin + s1->pos.x;
+				x_end = e1->bbox.xMax + e1->pos.x;
+
+				dt = (tm_current - tm_start);
+				if ((s1->effect_type == EF_KARAOKE) || (s1->effect_type == EF_KARAOKE_KO)) {
+					if (dt > 0)
+						x = x_end + 1;
+					else
+						x = x_start;
+				} else if (s1->effect_type == EF_KARAOKE_KF) {
+					dt /= (tm_end - tm_start);
+					x = x_start + (x_end - x_start) * dt;
+				} else {
+					mp_msg(MSGT_GLOBAL, MSGL_ERR, "Unknown effect type (internal error)  \n");
+					continue;
+				}
+
+				for (cur2 = s1; cur2 <= e1; ++cur2) {
+					cur2->effect_type = s1->effect_type;
+					cur2->effect_timing = x - cur2->pos.x;
+				}
+			}
+		}
+	}
+}
+
+int get_face_ascender(FT_Face face)
+{
+	int v = face->size->metrics.ascender;
+	if (!v)
+		v = FT_MulFix(face->bbox.yMax, face->size->metrics.y_scale);
+	return v;
+}
+
+int get_face_descender(FT_Face face)
+{
+	int v = face->size->metrics.descender;
+	if (!v)
+		v = FT_MulFix(face->bbox.yMin, face->size->metrics.y_scale);
+	return -v;
+}
+
+/**
+ * \brief Main ass rendering function, glues everything together
+ * \param event event to render
+ * Process event, appending resulting ass_image_t's to images_root.
+ */
+int ass_render_event(ass_event_t* event)
+{
+	char* p;
+	FT_UInt glyph_index; 
+	FT_Bool use_kerning; 
+	FT_UInt previous; 
+	FT_UInt num_glyphs;
+	FT_Vector pen;
+	int error;
+	unsigned code;
+	FT_BBox bbox;
+	int i, j;
+	FT_Vector shift;
+	int MarginL, MarginR, MarginV;
+	int max_text_width;
+	ass_style_t* style = frame_context.track->styles + event->Style;
+	int last_break;
+	int alignment, halign, valign;
+	int device_x, device_y;
+
+	init_render_context(event);
+
+	text_info.length = 0;
+	pen.x = 0;
+	pen.y = 0;
+	previous = 0;
+	num_glyphs = 0;
+
+	
+	p = event->Text;
+	if (!p) {
+		mp_msg(MSGT_GLOBAL, MSGL_WARN, "Empty event!\n");
+		return 0;
+	}
+
+	// Event parsing.
+	while (1) {
+		render_context.effect_type = EF_NONE;
+	
+		// get next char, executing style override
+		// this affects render_context
+		code = get_next_char(&p);
+		
+		// face could have been changed in get_next_char
+		if (!render_context.face) {
+			free_render_context();
+			return 0;
+		}
+
+		if (code == 0)
+			break;
+
+		use_kerning = FT_HAS_KERNING(render_context.face);
+
+		if (text_info.length >= MAX_GLYPHS) {
+			mp_msg(MSGT_GLOBAL, MSGL_WARN, "\nMAX_GLYPHS reached: event %d, start = %llu, duration = %llu\n Text = %s\n", 
+					(int)(event - frame_context.track->events), event->Start, event->Duration, event->Text);
+			break;
+		}
+
+		glyph_index = FT_Get_Char_Index( render_context.face, code);
+
+		if ( use_kerning && previous && glyph_index ) {
+			FT_Vector delta;
+			FT_Get_Kerning( render_context.face, previous, glyph_index, FT_KERNING_DEFAULT, &delta );
+			pen.x += delta.x;
+			pen.y += delta.y;
+		}
+
+		shift.x = pen.x & 63;
+		shift.y = pen.y & 63;
+
+		if ((render_context.scale_x != 1.) || (render_context.scale_y != 1.) ||
+				(frame_context.font_scale_x != 1.)) {
+			FT_Matrix matrix;
+			matrix.xx = (FT_Fixed)( render_context.scale_x * frame_context.font_scale_x * 0x10000L );
+			matrix.xy = (FT_Fixed)( 0 * 0x10000L );
+			matrix.yx = (FT_Fixed)( 0 * 0x10000L );
+			matrix.yy = (FT_Fixed)( render_context.scale_y * 0x10000L );
+
+			FT_Set_Transform( render_context.face, &matrix, &shift );
+		} else {
+			FT_Set_Transform(render_context.face, 0, &shift);
+		}
+		
+		error = get_glyph(glyph_index, code, text_info.glyphs + text_info.length, &shift);
+
+		if (error) {
+			continue;
+		}
+		
+		text_info.glyphs[text_info.length].pos.x = pen.x >> 6;
+		text_info.glyphs[text_info.length].pos.y = pen.y >> 6;
+		
+		pen.x += text_info.glyphs[text_info.length].advance.x;
+		pen.x += render_context.hspacing;
+		pen.y += text_info.glyphs[text_info.length].advance.y;
+		
+		// if it's an outline glyph, we still need to fill the bbox
+		if (text_info.glyphs[text_info.length].bitmap != 1) {
+			FT_Glyph_Get_CBox( text_info.glyphs[text_info.length].glyph, FT_GLYPH_BBOX_PIXELS, &(text_info.glyphs[text_info.length].bbox) );
+		}
+
+		
+		previous = glyph_index;
+		
+		text_info.glyphs[text_info.length].symbol = code;
+		text_info.glyphs[text_info.length].linebreak = 0;
+		text_info.glyphs[text_info.length].c1 = render_context.c1;
+		text_info.glyphs[text_info.length].c2 = render_context.c2;
+		text_info.glyphs[text_info.length].c3 = render_context.c3;
+		text_info.glyphs[text_info.length].c4 = render_context.c4;
+		text_info.glyphs[text_info.length].effect_type = render_context.effect_type;
+		text_info.glyphs[text_info.length].effect_timing = render_context.effect_timing;
+		text_info.glyphs[text_info.length].asc = get_face_ascender(render_context.face);
+		text_info.glyphs[text_info.length].desc = get_face_descender(render_context.face);
+
+		text_info.length++;
+	}
+	
+	if (text_info.length == 0) {
+		// no valid symbols in the event; this can be smth like {comment}
+		free_render_context();
+		return 0;
+	}
+	
+	// depends on glyph x coordinates being monotonous, so it should be done before line wrap
+	process_karaoke_effects();
+	
+	// calculate max length of a line
+	MarginL = (event->MarginL) ? event->MarginL : style->MarginL; 
+	MarginR = (event->MarginR) ? event->MarginR : style->MarginR; 
+	MarginV = (event->MarginV) ? event->MarginV : style->MarginV;
+
+	max_text_width = x2scr(frame_context.track->PlayResX - MarginR) - x2scr(MarginL);
+	mp_msg(MSGT_GLOBAL, MSGL_DBG2, "normal text width: %d\n", max_text_width);
+
+	// rearrange text in several lines
+	wrap_lines_smart(max_text_width);
+	
+	// alignments
+	alignment = render_context.alignment;
+	if (!alignment)
+		alignment = render_context.style->Alignment;
+	halign = alignment & 3;
+	valign = alignment & 12;
+
+	// align text
+	last_break = -1;
+	for (i = 1; i < text_info.length + 1; ++i) { // (text_info.length + 1) is the end of the last line
+		if ((i == text_info.length) || text_info.glyphs[i].linebreak) {
+
+			glyph_info_t* first_glyph = text_info.glyphs + last_break + 1;
+			glyph_info_t* last_glyph = text_info.glyphs + i - 1;
+
+			while ((last_glyph >= first_glyph) && ((last_glyph->symbol == '\n') || (last_glyph->symbol == 0)))
+				last_glyph --;
+
+			int width = last_glyph->pos.x + last_glyph->bbox.xMax - first_glyph->pos.x - first_glyph->bbox.xMin;
+			int shift = - first_glyph->bbox.xMin; // now text line starts exactly at 0 (left margin)
+			if (halign == HALIGN_LEFT) { // left aligned, no action
+			} else if (halign == HALIGN_RIGHT) { // right aligned
+				shift = max_text_width - width;
+			} else if (halign == HALIGN_CENTER) { // centered
+				shift = (max_text_width - width) / 2;
+			}
+			for (j = last_break + 1; j < i; ++j) {
+				text_info.glyphs[j].pos.x += shift;
+			}
+			last_break = i - 1;
+		}
+	}
+	
+	// determing text bounding box
+	compute_string_bbox(&text_info, &bbox);
+	
+	// determine device coordinates for text
+
+	// FIXME: using current font descender, ascender and height here is wrong.
+	// correct way is using max(descender) over all the fonts used in a line
+	// the same for height and ascender
+	if (render_context.evt_type == EVENT_NORMAL) {
+		device_x = x2scr(MarginL);
+		if (valign == VALIGN_TOP) { // toptitle
+			device_y = y2scr_top(MarginV) + (text_info.lines[0].asc >> 6);
+			if (render_context.detect_collisions) {
+				device_y += frame_context.add_top_margin;
+				frame_context.add_top_margin += (text_info.height >> 6);
+			}
+		} else if (valign == VALIGN_CENTER) { // midtitle
+			int scr_y = y2scr(frame_context.track->PlayResY / 2);
+			device_y = scr_y - (bbox.yMax - bbox.yMin) / 2;
+		} else { // subtitle
+			int scr_y;
+			if (valign != VALIGN_SUB)
+				mp_msg(MSGT_GLOBAL, MSGL_V, "Invalid valign, supposing 0 (subtitle)\n");
+			scr_y = y2scr_sub(frame_context.track->PlayResY - MarginV);
+			device_y = scr_y;
+			device_y -= (text_info.height >> 6);
+			device_y += (text_info.lines[0].asc >> 6);
+			if (render_context.detect_collisions) {
+				device_y -= frame_context.add_bottom_margin;
+				frame_context.add_bottom_margin += (text_info.height >> 6);
+			}
+		}
+	} else if (render_context.evt_type == EVENT_POSITIONED) {
+		int align_shift_x = 0;
+		int align_shift_y = 0;
+		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "positioned event at %d, %d\n", render_context.pos_x, render_context.pos_y);
+		switch(halign) {
+			case HALIGN_LEFT:
+				align_shift_x = - bbox.xMin;
+				break;
+			case HALIGN_CENTER:
+				align_shift_x = - (bbox.xMax + bbox.xMin) /2;
+				break;
+			case HALIGN_RIGHT:
+				align_shift_x = - bbox.xMax;
+				break;
+		}
+		switch(valign) {
+			case VALIGN_TOP:
+				align_shift_y = - bbox.yMin;
+				break;
+			case VALIGN_CENTER:
+				align_shift_y = - (bbox.yMax + bbox.yMin) /2;
+				break;
+			case VALIGN_SUB:
+				align_shift_y = - bbox.yMax;
+				break;
+		}
+		device_x = x2scr(render_context.pos_x) + align_shift_x;
+		device_y = y2scr(render_context.pos_y) + align_shift_y;
+	} else {
+		mp_msg(MSGT_GLOBAL, MSGL_V, "unknown evt_type\n");
+		device_x = 10;
+		device_y = 10;
+	}
+	
+	// fix clip coordinates (they depend on alignment)
+	render_context.clip_x0 = x2scr(render_context.clip_x0);
+	render_context.clip_x1 = x2scr(render_context.clip_x1);
+	if (render_context.evt_type == EVENT_NORMAL) {
+		if (valign == VALIGN_TOP) {
+			render_context.clip_y0 = y2scr_top(render_context.clip_y0);
+			render_context.clip_y1 = y2scr_top(render_context.clip_y1);
+		} else if (valign == VALIGN_CENTER) {
+			render_context.clip_y0 = y2scr(render_context.clip_y0);
+			render_context.clip_y1 = y2scr(render_context.clip_y1);
+		} else if (valign == VALIGN_SUB) {
+			render_context.clip_y0 = y2scr_sub(render_context.clip_y0);
+			render_context.clip_y1 = y2scr_sub(render_context.clip_y1);
+		}
+	} else if (render_context.evt_type == EVENT_POSITIONED) {
+		render_context.clip_y0 = y2scr(render_context.clip_y0);
+		render_context.clip_y1 = y2scr(render_context.clip_y1);
+	}
+
+	// rotate glyphs if needed
+	if (render_context.rotation != 0.) {
+		double angle = render_context.rotation;
+		FT_Vector center;
+		FT_Matrix matrix_rotate;
+		
+		matrix_rotate.xx = (FT_Fixed)( cos( angle ) * 0x10000L );
+		matrix_rotate.xy = (FT_Fixed)( -sin( angle ) * 0x10000L );
+		matrix_rotate.yx = (FT_Fixed)( sin( angle ) * 0x10000L );
+		matrix_rotate.yy = (FT_Fixed)( cos( angle ) * 0x10000L );
+		
+		if (((render_context.org_x != 0) || (render_context.org_y != 0)) && (render_context.evt_type == EVENT_POSITIONED)) {
+			center.x = render_context.org_x;
+			center.y = render_context.org_y;
+		} else {
+			FT_BBox str_bbox;
+
+			center.x = text_info.glyphs[0].pos.x + device_x;
+			center.y = text_info.glyphs[0].pos.y + device_y;
+
+			compute_string_bbox(&text_info, &str_bbox);
+			center.x += (str_bbox.xMax - str_bbox.xMin) / 2;
+			center.y += (str_bbox.yMax - str_bbox.yMin) / 2;
+		}
+//		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "\ncenter: %d, %d\n", center.x, center.y);
+
+		for (i = 0; i < text_info.length; ++i) {
+			glyph_info_t* info = text_info.glyphs + i;
+
+			// calculating shift vector
+			// shift = (position - center)*M - (position - center)
+			FT_Vector start;
+			FT_Vector start_old;
+//			mp_msg(MSGT_GLOBAL, MSGL_INFO, "start: (%d, %d) + (%d, %d) - (%d, %d) = (%d, %d)\n", info->pos.x, info->pos.y, device_x, device_y, center.x, center.y,
+//					info->pos.x + device_x - center.x, info->pos.y + device_y - center.y);
+			start.x = (info->pos.x + device_x - center.x) << 6;
+			start.y = - (info->pos.y + device_y - center.y) << 6;
+			start_old.x = start.x;
+			start_old.y = start.y;
+//			mp_msg(MSGT_GLOBAL, MSGL_INFO, "start: %d, %d\n", start.x / 64, start.y / 64);
+
+			FT_Vector_Transform(&start, &matrix_rotate);
+			
+			start.x -= start_old.x;
+			start.y -= start_old.y;
+
+			info->pos.x += start.x >> 6;
+			info->pos.y -= start.y >> 6;
+
+//			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "shift: %d, %d\n", start.x / 64, start.y / 64);
+			if (info->bitmap != 1) {
+				FT_Glyph_Transform( info->glyph, &matrix_rotate, 0 );
+				FT_Glyph_Transform( info->outline_glyph, &matrix_rotate, 0 );
+			}
+		}
+	}
+
+	// render
+	render_text(&text_info, device_x, device_y);
+
+	free_render_context();
+	
+	return 0;
+}
+
+void ass_configure(ass_instance_t* priv, const ass_settings_t* config)
+{
+	memcpy(&priv->settings, config, sizeof(ass_settings_t));
+}
+
+/**
+ * \brief Start a new frame
+ */
+int ass_start_frame(ass_instance_t *priv, ass_track_t* track, long long now)
+{
+	ass_instance = priv;
+	global_settings = &priv->settings;
+
+	if (!priv->settings.frame_width && !priv->settings.frame_height)
+		return 1; // library not initialized
+	
+	frame_context.ass_priv = priv;
+	frame_context.width = global_settings->frame_width;
+	frame_context.height = global_settings->frame_height;
+	frame_context.orig_height = global_settings->frame_height - global_settings->top_margin - global_settings->bottom_margin;
+	frame_context.track = track;
+	frame_context.add_bottom_margin = 0;
+	frame_context.add_top_margin = 0;
+	frame_context.time = now;
+
+	ass_lazy_track_init();
+	
+	if (frame_context.width * track->PlayResY == frame_context.height * track->PlayResX)
+		frame_context.font_scale_x = 1.;
+	else
+		frame_context.font_scale_x = ((double)(frame_context.width * track->PlayResY)) / (frame_context.height * track->PlayResX);
+
+	priv->n_images = 0;
+
+	return 0;
+}
+
+/**
+ * \brief End a frame, give out rendering results
+ * \return list of ass_image_t
+ */
+ass_image_t* ass_end_frame(void)
+{
+	ass_instance_t* priv = ass_instance;
+	if (priv->n_images) {
+		int i;
+		for (i = 0; i < priv->n_images - 1; ++i)
+			priv->images_root[i].next = priv->images_root + i + 1;
+		priv->images_root[priv->n_images - 1].next = 0;
+		return priv->images_root;
+	} else {
+		return 0;
+	}
+}
+/**
+ * \brief render a frame
+ * \param priv library handle
+ * \param track track
+ * \param now current video timestamp (ms)
+ */
+ass_image_t* ass_render_frame(ass_instance_t *priv, ass_track_t* track, long long now)
+{
+	int i, rc;
+	
+	rc = ass_start_frame(priv, track, now);
+	if (rc != 0) // some error
+		return 0;
+	for (i = 0; i < track->n_events; ++i) {
+		ass_event_t* event = track->events + i;
+		if ( (event->Start <= now) && (now < (event->Start + event->Duration)) ) {
+			ass_render_event(event);
+		}
+	}
+	return ass_end_frame();
+}
+

Added: trunk/libass/ass_types.h
==============================================================================
--- (empty file)
+++ trunk/libass/ass_types.h	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,83 @@
+#ifndef __ASS_TYPES_H__
+#define __ASS_TYPES_H__
+
+#define VALIGN_SUB 0
+#define VALIGN_CENTER 8
+#define VALIGN_TOP 4
+#define HALIGN_LEFT 1
+#define HALIGN_CENTER 2
+#define HALIGN_RIGHT 3
+
+/// ass Style: line
+typedef struct ass_style_s {
+	char* Name;
+	char* FontName;
+	int FontSize;
+	uint32_t PrimaryColour;
+	uint32_t SecondaryColour;
+	uint32_t OutlineColour;
+	uint32_t BackColour;
+	int Bold;
+	int Italic;
+	int Underline;
+	int StrikeOut;
+	double ScaleX;
+	double ScaleY;
+	int Spacing;
+	int Angle;
+	int BorderStyle;
+	double Outline;
+	double Shadow;
+	int Alignment;
+	int MarginL;
+	int MarginR;
+	int MarginV;
+//        int AlphaLevel;
+	int Encoding;
+} ass_style_t;
+
+/// ass_event_t corresponds to a single Dialogue line
+/// Text is stored as-is, style overrides will be parsed later
+typedef struct ass_event_s {
+	long long Start; // ms
+	long long Duration; // ms
+
+	int ReadOrder;
+	int Layer;
+	int Style;
+	char* Name;
+	int MarginL;
+	int MarginR;
+	int MarginV;
+	char* Effect;
+	char* Text;
+} ass_event_t;
+
+/// ass track represent either an external script or a matroska subtitle stream (no real difference between them)
+/// it can be used in rendering after the headers are parsed (i.e. events format line read)
+typedef struct ass_track_s {
+	int n_styles; // amount used
+	int max_styles; // amount allocated
+	int n_events;
+	int max_events;
+	ass_style_t* styles; // array of styles, max_styles length, n_styles used
+	ass_event_t* events; // the same as styles
+
+	char* style_format; // style format line (everything after "Format: ")
+	char* event_format; // event format line
+
+	enum {TRACK_TYPE_ASS, TRACK_TYPE_SSA} track_type;
+	
+	// script header fields
+	int PlayResX;
+	int PlayResY;
+	double Timer;
+	int WrapStyle;
+
+	
+	int default_style; // index of default style
+	char* name; // file name in case of external subs, 0 for streams
+} ass_track_t;
+
+#endif
+

Added: trunk/libass/ass_utils.c
==============================================================================
--- (empty file)
+++ trunk/libass/ass_utils.c	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,63 @@
+#include "config.h"
+
+#include <stdlib.h>
+#include <stdint.h>
+#include <sys/time.h>
+#include <time.h>
+
+#include "mp_msg.h"
+#include "ass_utils.h"
+
+int mystrtoi(char** p, int base, int* res)
+{
+	char* start = *p;
+	*res = strtol(*p, p, base);
+	if (*p != start) return 1;
+	else return 0;
+}
+
+int mystrtou32(char** p, int base, uint32_t* res)
+{
+	char* start = *p;
+	*res = strtoll(*p, p, base);
+	if (*p != start) return 1;
+	else return 0;
+}
+
+int mystrtod(char** p, double* res)
+{
+	char* start = *p;
+	*res = strtod(*p, p);
+	if (*p != start) return 1;
+	else return 0;
+}
+
+int strtocolor(char** q, uint32_t* res)
+{
+	uint32_t color = 0;
+	int result;
+	char* p = *q;
+	
+	if (*p == '&') ++p; 
+	else mp_msg(MSGT_GLOBAL, MSGL_V, "bad color: \"%s\"\n", p);
+	
+	if (*p == 'H') { 
+		++p;
+		result = mystrtou32(&p, 16, &color);
+	} else {
+		result = mystrtou32(&p, 10, &color);
+	}
+	
+	{
+		unsigned char* tmp = (unsigned char*)(&color);
+		unsigned char b;
+		b = tmp[0]; tmp[0] = tmp[3]; tmp[3] = b;
+		b = tmp[1]; tmp[1] = tmp[2]; tmp[2] = b;
+	}
+	if (*p == '&') ++p;
+	*q = p;
+
+	*res = color;
+	return result;
+}
+

Added: trunk/libass/ass_utils.h
==============================================================================
--- (empty file)
+++ trunk/libass/ass_utils.h	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,9 @@
+#ifndef __ASS_UTILS_H__
+#define __ASS_UTILS_H__
+
+int mystrtoi(char** p, int base, int* res);
+int mystrtou32(char** p, int base, uint32_t* res);
+int mystrtod(char** p, double* res);
+int strtocolor(char** q, uint32_t* res);
+#endif
+

Modified: trunk/libmpcodecs/Makefile
==============================================================================
--- trunk/libmpcodecs/Makefile	(original)
+++ trunk/libmpcodecs/Makefile	Fri Jul  7 20:26:51 2006
@@ -310,6 +310,10 @@
 ENCODER_SRCS += ae_faac.c
 endif
 
+ifeq ($(CONFIG_ASS),yes)
+VFILTER_SRCS += vf_ass.c
+endif
+
 SRCS=$(AUDIO_SRCS) \
      $(VIDEO_SRCS) \
      $(VFILTER_SRCS) \

Modified: trunk/libmpcodecs/vf.c
==============================================================================
--- trunk/libmpcodecs/vf.c	(original)
+++ trunk/libmpcodecs/vf.c	Fri Jul  7 20:26:51 2006
@@ -100,6 +100,7 @@
 extern vf_info_t vf_info_harddup;
 extern vf_info_t vf_info_softskip;
 extern vf_info_t vf_info_screenshot;
+extern vf_info_t vf_info_ass;
 extern vf_info_t vf_info_mcdeint;
 extern vf_info_t vf_info_yadif;
 
@@ -194,6 +195,9 @@
 #ifdef HAVE_PNG
     &vf_info_screenshot,
 #endif
+#ifdef USE_ASS
+    &vf_info_ass,
+#endif
     &vf_info_yadif,
     NULL
 };

Modified: trunk/libmpcodecs/vf.h
==============================================================================
--- trunk/libmpcodecs/vf.h	(original)
+++ trunk/libmpcodecs/vf.h	Fri Jul  7 20:26:51 2006
@@ -77,6 +77,7 @@
 #define VFCTRL_SKIP_NEXT_FRAME 12 /* For encoding - drop the next frame that passes thru */
 #define VFCTRL_FLUSH_FRAMES    13 /* For encoding - flush delayed frames */
 #define VFCTRL_SCREENSHOT      14 /* Make a screenshot */
+#define VFCTRL_EOSD            15 /* Select EOSD renderer */
 
 #include "vfcap.h"
 

Added: trunk/libmpcodecs/vf_ass.c
==============================================================================
--- (empty file)
+++ trunk/libmpcodecs/vf_ass.c	Fri Jul  7 20:26:51 2006
@@ -0,0 +1,435 @@
+#include "config.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+#include <assert.h>
+
+#include "config.h"
+#include "mp_msg.h"
+#include "help_mp.h"
+
+#include "img_format.h"
+#include "mp_image.h"
+#include "vf.h"
+
+#include "libvo/fastmemcpy.h"
+
+#include "m_option.h"
+#include "m_struct.h"
+
+#include "libass/ass.h"
+#include "libass/ass_mp.h"
+
+#define _r(c)  ((c)>>24)
+#define _g(c)  (((c)>>16)&0xFF)
+#define _b(c)  (((c)>>8)&0xFF)
+#define _a(c)  ((c)&0xFF)
+#define rgba2y(c)  ( (( 263*_r(c)  + 516*_g(c) + 100*_b(c)) >> 10) + 16  )
+#define rgba2u(c)  ( ((-152*_r(c) - 298*_g(c) + 450*_b(c)) >> 10) + 128 )
+#define rgba2v(c)  ( (( 450*_r(c) - 376*_g(c) -  73*_b(c)) >> 10) + 128 )
+
+
+static struct vf_priv_s {
+	int outh, outw;
+
+	unsigned int outfmt;
+
+	// 1 = auto-added filter: insert only if chain does not support EOSD already
+	// 0 = insert always
+	int auto_insert;
+
+	ass_instance_t* ass_priv;
+
+	unsigned char* planes[3];
+	unsigned char* dirty_rows;
+} vf_priv_dflt;
+
+extern int opt_screen_size_x;
+extern int opt_screen_size_y;
+
+extern ass_track_t* ass_track;
+extern float sub_delay;
+extern int sub_visibility;
+
+static int config(struct vf_instance_s* vf,
+	int width, int height, int d_width, int d_height,
+	unsigned int flags, unsigned int outfmt)
+{
+	ass_settings_t settings;
+	
+	if (outfmt == IMGFMT_IF09) return 0;
+
+	vf->priv->outh = height + ass_top_margin + ass_bottom_margin;
+	vf->priv->outw = width;
+
+	if(!opt_screen_size_x && !opt_screen_size_y){
+		d_width = d_width * vf->priv->outw / width;
+		d_height = d_height * vf->priv->outh / height;
+	} 
+
+	vf->priv->planes[1] = (unsigned char*)malloc(vf->priv->outw * vf->priv->outh);
+	vf->priv->planes[2] = (unsigned char*)malloc(vf->priv->outw * vf->priv->outh);
+	vf->priv->dirty_rows = (unsigned char*)malloc(vf->priv->outh);
+	
+	if (vf->priv->ass_priv) {
+		settings.frame_width = vf->priv->outw;
+		settings.frame_height = vf->priv->outh;
+		settings.font_size_coeff = ass_font_scale;
+		settings.line_spacing = ass_line_spacing;
+		settings.top_margin = ass_top_margin;
+		settings.bottom_margin = ass_bottom_margin;
+		settings.aspect = ((double)d_width) / d_height;
+		
+		ass_configure(vf->priv->ass_priv, &settings);
+	}
+
+	return vf_next_config(vf, vf->priv->outw, vf->priv->outh, d_width, d_height, flags, outfmt);
+}
+
+static void get_image(struct vf_instance_s* vf, mp_image_t *mpi)
+{
+	if(mpi->type == MP_IMGTYPE_IPB) return;
+	if(mpi->flags & MP_IMGFLAG_PRESERVE) return;
+	if(mpi->imgfmt != vf->priv->outfmt) return; // colorspace differ
+	    
+	// width never changes, always try full DR
+	mpi->priv = vf->dmpi = vf_get_image(vf->next, mpi->imgfmt,
+			mpi->type, mpi->flags, 
+			vf->priv->outw,
+			vf->priv->outh);
+
+	if((vf->dmpi->flags & MP_IMGFLAG_DRAW_CALLBACK) &&
+			!(vf->dmpi->flags & MP_IMGFLAG_DIRECT)){
+		mp_msg(MSGT_VFILTER, MSGL_INFO, MSGTR_MPCODECS_FullDRNotPossible);
+		return;
+	}
+
+	// set up mpi as a cropped-down image of dmpi:
+	if(mpi->flags&MP_IMGFLAG_PLANAR){
+		mpi->planes[0]=vf->dmpi->planes[0] + ass_top_margin * vf->dmpi->stride[0];
+		mpi->planes[1]=vf->dmpi->planes[1] + (ass_top_margin >> mpi->chroma_y_shift) * vf->dmpi->stride[1];
+		mpi->planes[2]=vf->dmpi->planes[2] + (ass_top_margin >> mpi->chroma_y_shift) * vf->dmpi->stride[2];
+		mpi->stride[1]=vf->dmpi->stride[1];
+		mpi->stride[2]=vf->dmpi->stride[2];
+	} else {
+		mpi->planes[0]=vf->dmpi->planes[0] + ass_top_margin * vf->dmpi->stride[0];
+	}
+	mpi->stride[0]=vf->dmpi->stride[0];
+	mpi->width=vf->dmpi->width;
+	mpi->flags|=MP_IMGFLAG_DIRECT;
+	mpi->flags&=~MP_IMGFLAG_DRAW_CALLBACK;
+//	vf->dmpi->flags&=~MP_IMGFLAG_DRAW_CALLBACK;
+}
+
+static void blank(mp_image_t *mpi, int y1, int y2)
+{
+	int color[3] = {16, 128, 128}; // black (YUV)
+	int y;
+	unsigned char* dst;
+	int chroma_rows = (y2 - y1) >> mpi->chroma_y_shift;
+
+	dst = mpi->planes[0] + y1 * mpi->stride[0];
+	for (y = 0; y < y2 - y1; ++y) {
+		memset(dst, color[0], mpi->w);
+		dst += mpi->stride[0];
+	}
+	dst = mpi->planes[1] + (y1 >> mpi->chroma_y_shift) * mpi->stride[1];
+	for (y = 0; y < chroma_rows ; ++y) {
+		memset(dst, color[1], mpi->chroma_width);
+		dst += mpi->stride[1];
+	}
+	dst = mpi->planes[2] + (y1 >> mpi->chroma_y_shift) * mpi->stride[2];
+	for (y = 0; y < chroma_rows ; ++y) {
+		memset(dst, color[2], mpi->chroma_width);
+		dst += mpi->stride[2];
+	}
+}
+
+static int prepare_image(struct vf_instance_s* vf, mp_image_t *mpi)
+{
+	if(mpi->flags&MP_IMGFLAG_DIRECT || mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
+		vf->dmpi = mpi->priv;
+		if (!vf->dmpi) { mp_msg(MSGT_VFILTER, MSGL_WARN, MSGTR_MPCODECS_FunWhydowegetNULL); return 0; }
+		mpi->priv = NULL;
+		// we've used DR, so we're ready...
+		if (ass_top_margin)
+			blank(vf->dmpi, 0, ass_top_margin);
+		if (ass_bottom_margin)
+			blank(vf->dmpi, vf->priv->outh - ass_bottom_margin, vf->priv->outh);
+		if(!(mpi->flags&MP_IMGFLAG_PLANAR))
+			vf->dmpi->planes[1] = mpi->planes[1]; // passthrough rgb8 palette
+		return 0;
+	}
+
+	// hope we'll get DR buffer:
+	vf->dmpi = vf_get_image(vf->next, vf->priv->outfmt,
+			MP_IMGTYPE_TEMP, MP_IMGFLAG_ACCEPT_STRIDE,
+			vf->priv->outw, vf->priv->outh);
+
+	// copy mpi->dmpi...
+	if(mpi->flags&MP_IMGFLAG_PLANAR){
+		memcpy_pic(vf->dmpi->planes[0] + ass_top_margin * vf->dmpi->stride[0],
+				mpi->planes[0], mpi->w, mpi->h,
+				vf->dmpi->stride[0], mpi->stride[0]);
+		memcpy_pic(vf->dmpi->planes[1] + (ass_top_margin >> mpi->chroma_y_shift) * vf->dmpi->stride[1],
+				mpi->planes[1], mpi->w >> mpi->chroma_x_shift, mpi->h >> mpi->chroma_y_shift,
+				vf->dmpi->stride[1], mpi->stride[1]);
+		memcpy_pic(vf->dmpi->planes[2] + (ass_top_margin >> mpi->chroma_y_shift) * vf->dmpi->stride[2],
+				mpi->planes[2], mpi->w >> mpi->chroma_x_shift, mpi->h >> mpi->chroma_y_shift,
+				vf->dmpi->stride[2], mpi->stride[2]);
+	} else {
+		memcpy_pic(vf->dmpi->planes[0] + ass_top_margin * vf->dmpi->stride[0],
+				mpi->planes[0], mpi->w*(vf->dmpi->bpp/8), mpi->h,
+				vf->dmpi->stride[0], mpi->stride[0]);
+		vf->dmpi->planes[1] = mpi->planes[1]; // passthrough rgb8 palette
+	}
+	if (ass_top_margin)
+		blank(vf->dmpi, 0, ass_top_margin);
+	if (ass_bottom_margin)
+		blank(vf->dmpi, vf->priv->outh - ass_bottom_margin, vf->priv->outh);
+	return 0;
+}
+
+/**
+ * \brief Copy specified rows from render_context.dmpi to render_context.planes, upsampling to 4:4:4
+ */
+static void copy_from_image(struct vf_instance_s* vf, int first_row, int last_row)
+{
+	int pl;
+	int i, j, k;
+	unsigned char val;
+	int chroma_rows;
+
+	first_row -= (first_row % 2);
+	last_row += (last_row % 2);
+	chroma_rows = (last_row - first_row) / 2;
+
+	for (pl = 1; pl < 3; ++pl) {
+		int dst_stride = vf->dmpi->stride[pl] * 2;
+		int src_stride = vf->dmpi->stride[pl];
+		
+		unsigned char* src = vf->dmpi->planes[pl] + (first_row/2) * src_stride;
+		unsigned char* dst = vf->priv->planes[pl] + first_row * dst_stride;
+		unsigned char* dst_next = dst + dst_stride;
+		for(i = 0; i < chroma_rows; ++i)
+		{
+			if ((vf->priv->dirty_rows[first_row + i*2] == 0) ||
+				(vf->priv->dirty_rows[first_row + i*2 + 1] == 0)) {
+				for (j = 0, k = 0; j < vf->dmpi->chroma_width; ++j, k+=2) {
+					val = *(src + j);
+					*(dst + k) = val;
+					*(dst + k + 1) = val;
+					*(dst_next + k) = val;
+					*(dst_next + k + 1) = val;
+				}
+			}
+			src += src_stride;
+			dst = dst_next + dst_stride;
+			dst_next = dst + dst_stride;
+		}
+	}
+	for (i = first_row; i < last_row; ++i)
+		vf->priv->dirty_rows[i] = 1;
+}
+
+/**
+ * \brief Copy all previously copied rows back to render_context.dmpi
+ */
+static void copy_to_image(struct vf_instance_s* vf)
+{
+	int pl;
+	int i, j, k;
+	for (pl = 1; pl < 3; ++pl) {
+		int dst_stride = vf->dmpi->stride[pl];
+		int src_stride = vf->dmpi->stride[pl] * 2;
+		
+		unsigned char* dst = vf->dmpi->planes[pl];
+		unsigned char* src = vf->priv->planes[pl];
+		unsigned char* src_next = vf->priv->planes[pl] + src_stride;
+		for(i = 0; i < vf->dmpi->chroma_height; ++i)
+		{
+			if ((vf->priv->dirty_rows[i*2] == 1)) {
+				assert(vf->priv->dirty_rows[i*2 + 1] == 1);
+				for (j = 0, k = 0; j < vf->dmpi->chroma_width; ++j, k+=2) {
+					unsigned val = 0;
+					val += *(src + k);
+					val += *(src + k + 1);
+					val += *(src_next + k);
+					val += *(src_next + k + 1);
+					*(dst + j) = val >> 2;
+				}
+			}
+			dst += dst_stride;
+			src = src_next + src_stride;
+			src_next = src + src_stride;
+		}
+	}
+}
+
+static void my_draw_bitmap(struct vf_instance_s* vf, unsigned char* bitmap, int bitmap_w, int bitmap_h, int stride, int dst_x, int dst_y, unsigned color)
+{
+	unsigned char y = rgba2y(color);
+	unsigned char u = rgba2u(color);
+	unsigned char v = rgba2v(color);
+	unsigned char opacity = 255 - _a(color);
+	unsigned char* src;
+	unsigned char* dst;
+	int i, j;
+	mp_image_t* dmpi = vf->dmpi;
+
+	
+	src = bitmap;
+	dst = dmpi->planes[0] + dst_x + dst_y * dmpi->stride[0];
+	for(i = 0; i < bitmap_h; ++i)
+	{
+		for (j = 0; j < bitmap_w; ++j) {
+		//	unsigned k = *(src+j);
+			unsigned k = ((unsigned)*(bitmap + stride * i + j)) * opacity / 255;
+			unsigned char orig_color = *(dst+j);
+			*(dst+j) = (k*y + (255-k)*orig_color) / 255;
+		}
+		src += stride;
+		dst += dmpi->stride[0];
+	}
+
+	for (i = 0; i < bitmap_h; ++i) {
+		for (j = 0; j < bitmap_w; ++j) {
+			int x = dst_x + j;
+			int y = dst_y + i;
+			unsigned k;
+			unsigned char orig_u, orig_v;
+			unsigned char new_u, new_v;
+
+			k = ((unsigned)*(bitmap + stride * i + j)) * opacity / 255;
+
+			orig_u = *(vf->priv->planes[1] + x + y * 2 * dmpi->chroma_width);
+			new_u = (k*u + (255-k)*orig_u) / 255;
+			*(vf->priv->planes[1] + x + y * 2 * dmpi->chroma_width) = new_u;
+
+			orig_v = *(vf->priv->planes[2] + x + y * 2 * dmpi->chroma_width);
+			new_v = (k*v + (255-k)*orig_v) / 255;
+			*(vf->priv->planes[2] + x + y * 2 * dmpi->chroma_width) = new_v;
+		}
+	} 
+}
+
+static int render_frame(struct vf_instance_s* vf, mp_image_t *mpi, const ass_image_t* img)
+{
+	if (img) {
+		memset(vf->priv->dirty_rows, 0, vf->priv->outh); // reset dirty rows
+		while (img) {
+			copy_from_image(vf, img->dst_y, img->dst_y + img->h);
+			my_draw_bitmap(vf, img->bitmap, img->w, img->h, img->stride,
+					img->dst_x, img->dst_y, img->color);
+			img = img->next;
+		}
+		copy_to_image(vf);
+	}
+	return 0;
+}
+
+static int put_image(struct vf_instance_s* vf, mp_image_t *mpi, double pts)
+{
+	ass_image_t* images = 0;
+	if (sub_visibility && vf->priv->ass_priv && ass_track && (pts != MP_NOPTS_VALUE))
+		images = ass_render_frame(vf->priv->ass_priv, ass_track, (pts+sub_delay) * 1000 + .5);
+	
+	prepare_image(vf, mpi);
+	if (images) render_frame(vf, mpi, images);
+
+	return vf_next_put_image(vf, vf->dmpi, pts);
+}
+
+static int query_format(struct vf_instance_s* vf, unsigned int fmt)
+{
+	switch(fmt){
+	case IMGFMT_YV12:
+	case IMGFMT_I420:
+	case IMGFMT_IYUV:
+		return vf_next_query_format(vf, vf->priv->outfmt);
+	}
+	return 0;
+}
+
+static int control(vf_instance_t *vf, int request, void *data)
+{
+	if (request == VFCTRL_EOSD) {
+		vf->priv->ass_priv = ass_init();
+		if (!vf->priv->ass_priv) {
+			mp_msg(MSGT_VFILTER, MSGL_ERR, "[ass] init failed\n");
+			return 0;
+		} else
+			mp_msg(MSGT_VFILTER, MSGL_INFO, "[ass] init\n");
+		return CONTROL_TRUE;
+	}
+	return vf_next_control(vf, request, data);
+}
+
+static void uninit(struct vf_instance_s* vf)
+{
+	if (vf->priv->ass_priv)
+		ass_done(vf->priv->ass_priv);
+	if (vf->priv->planes[1])
+		free(vf->priv->planes[1]);
+	if (vf->priv->planes[2])
+		free(vf->priv->planes[2]);
+	if (vf->priv->dirty_rows)
+		free(vf->priv->dirty_rows);
+}
+
+static unsigned int fmt_list[]={
+	IMGFMT_YV12,
+	IMGFMT_I420,
+	IMGFMT_IYUV,
+	0
+};
+
+static int open(vf_instance_t *vf, char* args)
+{
+	int flags;
+	vf->priv->outfmt = vf_match_csp(&vf->next,fmt_list,IMGFMT_YV12);
+	if (vf->priv->outfmt)
+		flags = vf_next_query_format(vf, vf->priv->outfmt);
+	if (!vf->priv->outfmt || (vf->priv->auto_insert && flags&VFCAP_EOSD))
+	{
+		uninit(vf);
+		return 0;
+	}
+	
+	if (vf->priv->auto_insert)
+		mp_msg(MSGT_VFILTER, MSGL_INFO, "[ass] auto-open\n");
+	
+	vf->config = config;
+	vf->query_format = query_format;
+	vf->uninit = uninit;
+	vf->control = control;
+	vf->get_image = get_image;
+	vf->put_image = put_image;
+	vf->default_caps=VFCAP_EOSD;
+	return 1;
+}
+
+#define ST_OFF(f) M_ST_OFF(struct vf_priv_s,f)
+static m_option_t vf_opts_fields[] = {
+	{"auto", ST_OFF(auto_insert), CONF_TYPE_FLAG, 0 , 0, 1, NULL},
+	{ NULL, NULL, 0, 0, 0, 0,  NULL }
+};
+
+static m_struct_t vf_opts = {
+	"ass",
+	sizeof(struct vf_priv_s),
+	&vf_priv_dflt,
+	vf_opts_fields
+};
+
+vf_info_t vf_info_ass = {
+	"Render ASS/SSA subtitles",
+	"ass",
+	"Evgeniy Stepanov",
+	"",
+	open,
+	&vf_opts
+};
+

Modified: trunk/libmpcodecs/vfcap.h
==============================================================================
--- trunk/libmpcodecs/vfcap.h	(original)
+++ trunk/libmpcodecs/vfcap.h	Fri Jul  7 20:26:51 2006
@@ -26,4 +26,6 @@
 #define VFCAP_POSTPROC 0x800
 // filter cannot be reconfigured to different size & format
 #define VFCAP_CONSTANT 0x1000
+// filter can draw EOSD
+#define VFCAP_EOSD 0x2000
 

Modified: trunk/libmpdemux/demux_mkv.c
==============================================================================
--- trunk/libmpdemux/demux_mkv.c	(original)
+++ trunk/libmpdemux/demux_mkv.c	Fri Jul  7 20:26:51 2006
@@ -23,6 +23,9 @@
 #include "subreader.h"
 #include "libvo/sub.h"
 
+#include "libass/ass.h"
+#include "libass/ass_mp.h"
+
 #ifdef USE_QTX_CODECS
 #include "qtx/qtxsdk/components.h"
 #endif
@@ -128,7 +131,7 @@
   mkv_content_encoding_t *encodings;
   int num_encodings;
 
-  /* For VobSubs */
+  /* For VobSubs and SSA/ASS */
   sh_sub_t sh_sub;
 } mkv_track_t;
 
@@ -143,6 +146,15 @@
   uint64_t start, end;
 } mkv_chapter_t;
 
+typedef struct mkv_attachment
+{
+  char* name;
+  char* mime;
+  uint64_t uid;
+  void* data;
+  unsigned int data_size;
+} mkv_attachment_t;
+
 typedef struct mkv_demuxer
 {
   off_t segment_start;
@@ -182,6 +194,9 @@
   
   int last_aid;
   int audio_tracks[MAX_A_STREAMS];
+  
+  mkv_attachment_t *attachments;
+  int num_attachments;
 } mkv_demuxer_t;
 
 
@@ -1424,6 +1439,119 @@
 }
 
 static int
+demux_mkv_read_attachments (demuxer_t *demuxer)
+{
+  mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
+  stream_t *s = demuxer->stream;
+  uint64_t length, l;
+  int il;
+
+  mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] /---- [ parsing attachments ] ---------\n");
+  length = ebml_read_length (s, NULL);
+
+  while (length > 0)
+    {
+      switch (ebml_read_id (s, &il))
+        {
+          case MATROSKA_ID_ATTACHEDFILE:
+            {
+              uint64_t len;
+              int i;
+              char* name = NULL;
+              char* mime = NULL;
+              uint64_t uid = 0;
+              char* data = NULL;
+              int data_size = 0;
+
+              len = ebml_read_length (s, &i);
+              l = len + i;
+
+              mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] | + an attachment...\n");
+
+              if (mkv_d->attachments == NULL)
+                mkv_d->attachments = malloc (32*sizeof(*mkv_d->attachments));
+              else if (!(mkv_d->num_attachments % 32))
+                mkv_d->attachments = realloc (mkv_d->attachments,
+                                           (mkv_d->num_attachments + 32)
+                                           * sizeof(*mkv_d->attachments));
+
+              while (len > 0)
+                {
+                  uint64_t l;
+                  int il;
+
+                  switch (ebml_read_id (s, &il))
+                    {
+                    case MATROSKA_ID_FILENAME:
+                      name = ebml_read_utf8 (s, &l);
+                      if (name == NULL)
+                        return 0;
+                      mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |  + FileName: %s\n",
+                        name);
+                      break;
+
+                    case MATROSKA_ID_FILEMIMETYPE:
+                      mime = ebml_read_ascii (s, &l);
+                      if (mime == NULL)
+                        return 0;
+                      mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |  + FileMimeType: %s\n",
+                        mime);
+                      break;
+
+                    case MATROSKA_ID_FILEUID:
+                      uid = ebml_read_uint (s, &l);
+                      break;
+
+                    case MATROSKA_ID_FILEDATA:
+                      {
+                        int x;
+                        uint64_t num = ebml_read_length (s, &x);
+                        l = x + num;
+                        data = malloc (num);
+                        if (stream_read(s, data, num) != (int) num)
+                          return 0;
+                        data_size = num;
+                        mp_msg (MSGT_DEMUX, MSGL_V, "[mkv] |  + FileData, length "
+                                "%u\n", data_size);
+                        break;
+                      }
+
+                    default:
+                      ebml_read_skip (s, &l);
+                      break;
+                    }
+                  len -= l + il;
+                }
+
+              mkv_d->attachments[mkv_d->num_attachments].name = name;
+              mkv_d->attachments[mkv_d->num_attachments].mime = mime;
+              mkv_d->attachments[mkv_d->num_attachments].uid = uid;
+              mkv_d->attachments[mkv_d->num_attachments].data = data;
+              mkv_d->attachments[mkv_d->num_attachments].data_size = data_size;
+              mkv_d->num_attachments ++;
+              mp_msg(MSGT_DEMUX, MSGL_V,
+                     "[mkv] Attachment: %s, %s, %u bytes\n",
+                     name, mime, data_size);
+#ifdef USE_ASS
+              if (extract_embedded_fonts && name && data && data_size &&
+                  mime && (strcmp(mime, "application/x-truetype-font") == 0))
+                ass_process_font(name, data, data_size);
+#endif
+              break;
+            }
+
+          default:
+            ebml_read_skip (s, &l);
+            break;
+        }
+      length -= l + il;
+    }
+
+  mp_msg(MSGT_DEMUX, MSGL_V, "[mkv] \\---- [ parsing attachments ] ---------\n");
+  return 0;
+}
+
+static int
 demux_mkv_read_seekhead (demuxer_t *demuxer)
 {
   mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
@@ -2115,12 +2243,52 @@
     }
 }
 
+/** \brief Parse the private data for SSA/ASS subtitle tracks.
+
+  This function tries to parse the private data for all SSA/ASS tracks.
+  The private data contains the normal text from the original script,
+  from the start to the beginning of 'Events' section, including '[Events]' line.
+
+  \param demuxer The generic demuxer.
+*/
+#ifdef USE_ASS
+static void
+demux_mkv_parse_ass_data (demuxer_t *demuxer)
+{
+  mkv_demuxer_t *mkv_d = (mkv_demuxer_t *) demuxer->priv;
+  mkv_track_t *track;
+  int i, m, size;
+  uint8_t *buffer;
+
+  for (i = 0; i < mkv_d->num_tracks; i++)
+    {
+      track = mkv_d->tracks[i];
+      if ((track->type != MATROSKA_TRACK_SUBTITLE) ||
+          (track->subtitle_type != MATROSKA_SUBTYPE_SSA))
+        continue;
+
+      size = track->private_size;
+      m = demux_mkv_decode (track,track->private_data,&buffer,&size,2);
+      if (buffer && m)
+        {
+          free (track->private_data);
+          track->private_data = buffer;
+          track->private_size = size;
+        }
+      track->sh_sub.type = 'a';
+      track->sh_sub.ass_track = ass_new_track();
+      ass_process_chunk(track->sh_sub.ass_track, track->private_data, track->private_size);
+    }
+}
+#endif
+
 static int
 demux_mkv_open_sub (demuxer_t *demuxer, mkv_track_t *track)
 {
   if (track->subtitle_type != MATROSKA_SUBTYPE_UNKNOWN)
     {
-      if (track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB)
+      if ((track->subtitle_type == MATROSKA_SUBTYPE_VOBSUB) ||
+          (track->subtitle_type == MATROSKA_SUBTYPE_SSA))
         {
           if (track->private_data != NULL)
             {
@@ -2237,6 +2405,10 @@
           cont = demux_mkv_read_chapters (demuxer);
           break;
 
+        case MATROSKA_ID_ATTACHMENTS:
+          cont = demux_mkv_read_attachments (demuxer);
+          break;
+
         case MATROSKA_ID_CLUSTER:
           {
             int p, l;
@@ -2266,7 +2438,6 @@
 
         default:
           cont = 1;
-        case MATROSKA_ID_ATTACHMENTS:
         case EBML_ID_VOID:
           ebml_read_skip (s, NULL);
           break;
@@ -2373,6 +2544,10 @@
     }
 
   demux_mkv_parse_vobsub_data (demuxer);
+#ifdef USE_ASS
+  if (ass_enabled)
+    demux_mkv_parse_ass_data (demuxer);
+#endif
   /* DO NOT automatically select a subtitle track and behave like DVD */
   /* playback: only show subtitles if the user explicitely wants them. */
   track = NULL;
@@ -2457,6 +2632,10 @@
                 free (mkv_d->tracks[i]->audio_buf);
               if (mkv_d->tracks[i]->audio_timestamp)
                 free (mkv_d->tracks[i]->audio_timestamp);
+#ifdef USE_ASS
+              if (mkv_d->tracks[i]->sh_sub.ass_track)
+                ass_free_track (mkv_d->tracks[i]->sh_sub.ass_track);
+#endif
             }
           for (i=0; i < SUB_MAX_TEXT; i++)
             if (mkv_d->subs.text[i])
@@ -2473,6 +2652,17 @@
         free (mkv_d->parsed_cues);
       if (mkv_d->parsed_seekhead)
         free (mkv_d->parsed_seekhead);
+      if (mkv_d->attachments) {
+        for (i = 0; i < mkv_d->num_attachments; ++i) {
+          if (mkv_d->attachments[i].name)
+            free (mkv_d->attachments[i].name);
+          if (mkv_d->attachments[i].mime)
+            free (mkv_d->attachments[i].mime);
+          if (mkv_d->attachments[i].data)
+            free (mkv_d->attachments[i].data);
+        }
+        free (mkv_d->attachments);
+      }
       free (mkv_d);
     }
 }
@@ -2578,6 +2768,13 @@
       return;
     }
 
+#ifdef USE_ASS
+  if (ass_enabled && track->subtitle_type == MATROSKA_SUBTYPE_SSA) {
+    ass_process_line(track->sh_sub.ass_track, block, size, (long long)timecode, (long long)block_duration);
+    return;
+  }
+#endif
+
   ptr1 = block;
   while (ptr1 - block <= size && (*ptr1 == '\n' || *ptr1 == '\r'))
     ptr1++;

Modified: trunk/libmpdemux/demuxer.h
==============================================================================
--- trunk/libmpdemux/demuxer.h	(original)
+++ trunk/libmpdemux/demuxer.h	Fri Jul  7 20:26:51 2006
@@ -1,6 +1,10 @@
 #ifndef __DEMUXER_H
 #define __DEMUXER_H 1
 
+#ifdef USE_ASS
+#include "libass/ass_types.h"
+#endif
+
 #define MAX_PACKS 4096
 #ifdef HAVE_TV_BSDBT848
 #define MAX_PACK_BYTES 0x2000000
@@ -122,13 +126,16 @@
 } demuxer_info_t;
 
 typedef struct {
-  char type;                    // t = text, v = VobSub
+  char type;                    // t = text, v = VobSub, a = SSA/ASS
   int has_palette;              // If we have a valid palette
   unsigned int palette[16];     // for VobSubs
   int width, height;            // for VobSubs
   int custom_colors;
   unsigned int colors[4];
   int forced_subs_only;
+#ifdef USE_ASS
+  ass_track_t* ass_track;  // for SSA/ASS streams (type == 'a')
+#endif
 } sh_sub_t;
 
 #define MAX_A_STREAMS 256

Modified: trunk/libmpdemux/ebml.h
==============================================================================
--- trunk/libmpdemux/ebml.h	(original)
+++ trunk/libmpdemux/ebml.h	Fri Jul  7 20:26:51 2006
@@ -138,6 +138,12 @@
 #define MATROSKA_ID_BLOCK                0xA1
 #define MATROSKA_ID_REFERENCEBLOCK       0xFB
 
+/* IDs in the attachments master */
+#define MATROSKA_ID_ATTACHEDFILE	 0x61A7
+#define MATROSKA_ID_FILENAME		 0x466E
+#define MATROSKA_ID_FILEMIMETYPE	 0x4660
+#define MATROSKA_ID_FILEDATA		 0x465C
+#define MATROSKA_ID_FILEUID		 0x46AE
 
 /* matroska track types */
 #define MATROSKA_TRACK_VIDEO    0x01 /* rectangle-shaped pictures aka video */

Modified: trunk/mencoder.c
==============================================================================
--- trunk/mencoder.c	(original)
+++ trunk/mencoder.c	Fri Jul  7 20:26:51 2006
@@ -223,6 +223,13 @@
   return 0;
 }
 
+#ifdef USE_ASS
+#include "libass/ass.h"
+#include "libass/ass_mp.h"
+
+ass_track_t* ass_track = 0; // current track to render
+#endif
+
 //char *out_audio_codec=NULL; // override audio codec
 //char *out_video_codec=NULL; // override video codec
 

Modified: trunk/mplayer.c
==============================================================================
--- trunk/mplayer.c	(original)
+++ trunk/mplayer.c	Fri Jul  7 20:26:51 2006
@@ -349,6 +349,16 @@
 #define SUB_SOURCES 3
 int global_sub_indices[SUB_SOURCES];
 
+#ifdef USE_ASS
+#include "libass/ass.h"
+#include "libass/ass_mp.h"
+
+// set_of_ass_tracks[i] contains subtitles from set_of_subtitles[i] parsed by libass
+// or NULL if format unsupported
+ass_track_t* set_of_ass_tracks[MAX_SUBTITLE_FILES];
+ass_track_t* ass_track = 0; // current track to render
+#endif
+
 extern int mp_msg_levels[MSGT_MAX];
 extern int mp_msg_level_all;
 
@@ -792,15 +802,30 @@
 void add_subtitles(char *filename, float fps, int silent)
 {
     sub_data *subd;
+#ifdef USE_ASS
+    ass_track_t *asst = 0;
+#endif
 
-    if (filename == NULL) {
+    if (filename == NULL || set_of_sub_size >= MAX_SUBTITLE_FILES) {
 	return;
     }
 
     subd = sub_read_file(filename, fps);
+#ifdef USE_ASS
+    if (ass_enabled)
+        asst = ass_read_file(filename);
+    if (!asst && !subd && !silent)
+#else
     if(!subd && !silent) 
+#endif
         mp_msg(MSGT_CPLAYER, MSGL_ERR, MSGTR_CantLoadSub, filename);
-    if (subd == NULL || set_of_sub_size >= MAX_SUBTITLE_FILES) return;
+    
+#ifdef USE_ASS
+    if (!asst && !subd) return;
+    set_of_ass_tracks[set_of_sub_size] = asst;
+#else
+    if (!subd) return;
+#endif
     set_of_subtitles[set_of_sub_size] = subd;
     mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", set_of_sub_size);
     mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n", filename);
@@ -1816,6 +1841,7 @@
 /// Selected subtitles (RW)
 static int mp_property_sub(m_option_t* prop,int action,void* arg) {
     int source = -1, reset_spu = 0;
+    char* sub_name;
 
     if(global_sub_size <= 0) return M_PROPERTY_UNAVAILABLE;
 
@@ -1828,10 +1854,19 @@
         if(!arg) return 0;
         *(char**)arg = malloc(64);
         (*(char**)arg)[63] = 0;
+        sub_name = 0;
 #ifdef USE_SUB
-        if(subdata) {
+        if(subdata)
+            sub_name = subdata->filename;
+#endif
+#ifdef USE_ASS
+        if (ass_track && ass_track->name)
+            sub_name = ass_track->name;
+#endif
+#if defined(USE_SUB) || defined(USE_ASS)
+        if(sub_name) {
             char *tmp,*tmp2;
-            tmp = subdata->filename;
+            tmp = sub_name;
             if ((tmp2 = strrchr(tmp, '/')))
                 tmp = tmp2+1;
 
@@ -1922,14 +1957,24 @@
         if(d_dvdsub->id > -2) reset_spu = 1;
         d_dvdsub->id = -2;
     }
+#ifdef USE_ASS
+    ass_track = 0;
+#endif
 
     if (source == SUB_SOURCE_VOBSUB) {
         vobsub_id = global_sub_pos - global_sub_indices[SUB_SOURCE_VOBSUB];
 #ifdef USE_SUB
     } else if (source == SUB_SOURCE_SUBS) {
         set_of_sub_pos = global_sub_pos - global_sub_indices[SUB_SOURCE_SUBS];
+#ifdef USE_ASS
+        if (ass_enabled && set_of_ass_tracks[set_of_sub_pos])
+            ass_track = set_of_ass_tracks[set_of_sub_pos];
+        else 
+#endif
+        {
         subdata = set_of_subtitles[set_of_sub_pos];
         vo_osd_changed(OSDTYPE_SUBTITLE);
+        }
 #endif
     } else if (source == SUB_SOURCE_DEMUX) {
         dvdsub_id = global_sub_pos - global_sub_indices[SUB_SOURCE_DEMUX];
@@ -1946,6 +1991,12 @@
 #endif
             if (demuxer->type == DEMUXER_TYPE_MATROSKA) {
                 d_dvdsub->id = demux_mkv_change_subs(demuxer, dvdsub_id);
+#ifdef USE_ASS
+                if (ass_enabled && (d_dvdsub->id >= 0) &&
+                        (((sh_sub_t *)d_dvdsub->sh)->type == 'a')) {
+                    ass_track = ((sh_sub_t *)d_dvdsub->sh)->ass_track;
+                }
+#endif
                 if (d_dvdsub->id >= 0 &&
                     ((sh_sub_t *)d_dvdsub->sh)->type == 'v') {
                     sh_sub_t *mkv_sh_sub = (sh_sub_t *)d_dvdsub->sh;
@@ -3554,11 +3605,37 @@
   }
 }
 if(vf_menu)
-  sh_video->vfilter=(void*)append_filters(vf_menu);
-else
+  sh_video->vfilter=(void*)vf_menu;
+#endif
+#ifdef USE_ASS
+if(ass_enabled) {
+  int i;
+  int insert = 1;
+  if (vf_settings)
+    for (i = 0; vf_settings[i].name; ++i)
+      if (strcmp(vf_settings[i].name, "ass") == 0) {
+        insert = 0;
+        break;
+      }
+  if (insert) {
+    extern vf_info_t vf_info_ass;
+    vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
+    char* vf_arg[] = {"auto", "1", NULL};
+    vf_instance_t* vf_ass = vf_open_plugin(libass_vfs,sh_video->vfilter,"ass",vf_arg);
+    if (vf_ass)
+      sh_video->vfilter=(void*)vf_ass;
+    else
+      mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
+  }
+}
 #endif
 sh_video->vfilter=(void*)append_filters(sh_video->vfilter);
 
+#ifdef USE_ASS
+if (ass_enabled)
+  ((vf_instance_t *)sh_video->vfilter)->control(sh_video->vfilter, VFCTRL_EOSD, 0);
+#endif
+
 current_module="init_video_codec";
 
 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
@@ -3835,7 +3912,7 @@
 	// decode:
 	current_module="decode_video";
 //	printf("Decode! %p  %d  \n",start,in_size);
-	blit_frame=decode_video(sh_video,start,in_size,drop_frame, MP_NOPTS_VALUE);
+	blit_frame=decode_video(sh_video,start,in_size,drop_frame, sh_video->pts);
 	break;
     }
     else while (1) {
@@ -4421,6 +4498,10 @@
     if (sh_video) {
       int movement = cmd->args[0].v.i;
       step_sub(subdata, sh_video->pts, movement);
+#ifdef USE_ASS
+      if (ass_track)
+        sub_delay += ass_step_sub(ass_track, (sh_video->pts + sub_delay) * 1000 + .5, movement) / 1000.;
+#endif
       set_osd_msg(OSD_MSG_SUB_DELAY,1,osd_duration,
                   MSGTR_OSDSubDelay, ROUND(sub_delay*1000));
     }
@@ -5001,11 +5082,19 @@
   if ( set_of_sub_size > 0 ) 
    {
     current_module="sub_free";
-    for (i = 0; i < set_of_sub_size; ++i)
+    for (i = 0; i < set_of_sub_size; ++i) {
         sub_free( set_of_subtitles[i] );
+#ifdef USE_ASS
+        if ( set_of_ass_tracks[i] )
+            ass_free_track( set_of_ass_tracks[i] );
+#endif
+    }
     set_of_sub_size = 0;
     vo_sub_last = vo_sub=NULL;
     subdata=NULL;
+#ifdef USE_ASS
+    ass_track = NULL;
+#endif
    }
 #endif
 



More information about the MPlayer-cvslog mailing list