<commit_before>#include "config.h"

#include <assert.h>
#include <math.h>
#include <inttypes.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_bitmap.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

static int last_render_id = 0;

struct ass_instance_s {
	FT_Library library;
	fc_instance_t* fontconfig_priv;
	ass_settings_t settings;
	int render_id;
	ass_synth_priv_t* synth_priv;

	ass_image_t* images_root; // rendering result is stored here
};

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;
	bitmap_t* bm;
	bitmap_t* bm_o;
	FT_BBox bbox;
	FT_Vector pos;
	char linebreak; // the first (leading) glyph of some line ?
	uint32_t c[4]; // colors
	FT_Vector advance; // 26.6
	effect_t effect_type;
	int effect_timing; // time duration of current karaoke word
	                   // after process_karaoke_effects: distance in pixels from the glyph origin.
	                   // part of the glyph to the left of it is displayed in a different color.
	int effect_skip_timing; // delay after the end of last karaoke word
	int asc, desc; // font max ascender and descender
//	int height;
	int be; // blur edges
	
	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
		EVENT_HSCROLL, // "Banner" transition effect, text_width is unlimited
		EVENT_VSCROLL // "Scroll up", "Scroll down" transition effects
		} 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 c[4]; // colors(Primary, Secondary, so on) in RGBA
	int clip_x0, clip_y0, clip_x1, clip_y1;
	char detect_collisions;
	uint32_t fade; // alpha from \fad
	char be; // blur edges

	effect_t effect_type;
	int effect_timing;
	int effect_skip_timing;

	enum { SCROLL_LR, // left-to-right
	       SCROLL_RL,
	       SCROLL_TB, // top-to-bottom
	       SCROLL_BT
	       } scroll_direction; // for EVENT_HSCROLL, EVENT_VSCROLL
	int scroll_shift;

	// 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 )
	int orig_width; // frame width ( = screen width - margins )
	ass_track_t* track;
	long long time; // frame's timestamp, ms
	double font_scale;
	double font_scale_x; // x scale applied to all glyphs to preserve text aspect ratio
	double border_scale;
} 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;

// a rendered event
typedef struct event_images_s {
	ass_image_t* imgs;
	int top, height;
	int detect_collisions;
	int shift_direction;
	ass_event_t* event;
} event_images_t;

struct render_priv_s {
	int top, height;
	int render_id;
};

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_width) /
			frame_context.orig_height / frame_context.width;
		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 = 0;
	
	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)
		goto ass_init_exit;
	
	error = FT_Init_FreeType( &ft );
	if ( error ) { 
		mp_msg(MSGT_GLOBAL, MSGL_FATAL, "FT_Init_FreeType failed\n");
		fontconfig_done(fc_priv);
		goto ass_init_exit;
	}

	priv = calloc(1, sizeof(ass_instance_t));
	if (!priv) {
		FT_Done_FreeType(ft);
		fontconfig_done(fc_priv);
		goto ass_init_exit;
	}

	priv->synth_priv = ass_synth_init();

	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));
	
ass_init_exit:
	if (priv) mp_msg(MSGT_GLOBAL, MSGL_INFO, "[ass] Init\n");
	else mp_msg(MSGT_GLOBAL, MSGL_ERR, "[ass] Init failed\n");

	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 && priv->synth_priv) ass_synth_done(priv->synth_priv);
	if (priv) free(priv);
	if (text_info.glyphs) free(text_info.glyphs);
}

/**
 * \brief Create a new ass_image_t
 * Parameters are the same as ass_image_t fields.
 */
static ass_image_t* my_draw_bitmap(unsigned char* bitmap, int bitmap_w, int bitmap_h, int stride, int dst_x, int dst_y, uint32_t color)
{
	ass_image_t* img = calloc(1, sizeof(ass_image_t));
	
	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;

	return img;
}

/**
 * \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
 * \param tail pointer to the last image's next field, head of the generated list should be stored here
 * \return pointer to the new list tail
 * Performs clipping. Uses my_draw_bitmap for actual bitmap convertion.
 */
static ass_image_t** render_glyph(bitmap_t* bm, int dst_x, int dst_y, uint32_t color, uint32_t color2, int brk, ass_image_t** tail)
{
	// 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;
	ass_image_t* img;

	dst_x += bm->left;
	dst_y += bm->top;
	brk -= bm->left;
	
	// 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 = bm->w;
	b_y1 = bm->h;
	
	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 - bm->w;
	if (tmp < 0) {
		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip right\n");
		b_x1 = bm->w + tmp;
	}
	tmp = clip_y1 - dst_y - bm->h;
	if (tmp < 0) {
		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip bottom\n");
		b_y1 = bm->h + tmp;
	}
	
	if ((b_y0 >= b_y1) || (b_x0 >= b_x1))
		return tail;

	if (brk > b_x0) { // draw left part
		if (brk > b_x1) brk = b_x1;
		img = my_draw_bitmap(bm->buffer + bm->w * b_y0 + b_x0, 
			brk - b_x0, b_y1 - b_y0, bm->w,
			dst_x + b_x0, dst_y + b_y0, color);
		*tail = img;
		tail = &img->next;
	}
	if (brk < b_x1) { // draw right part
		if (brk < b_x0) brk = b_x0;
		img = my_draw_bitmap(bm->buffer + bm->w * b_y0 + brk, 
			b_x1 - brk, b_y1 - b_y0, bm->w,
			dst_x + brk, dst_y + b_y0, color2);
		*tail = img;
		tail = &img->next;
	}
	return tail;
}

/**
 * \brief Render text_info_t struct into ass_images_t list
 * Rasterize glyphs and put them in glyph cache.
 */
static ass_image_t* render_text(text_info_t* text_info, int dst_x, int dst_y)
{
	int pen_x, pen_y;
	int i, error;
	bitmap_t* bm;
	glyph_hash_val_t hash_val;
	ass_image_t* head;
	ass_image_t** tail = &head;

	for (i = 0; i < text_info->length; ++i) {
		if (text_info->glyphs[i].glyph) {
			if ((text_info->glyphs[i].symbol == '\n') || (text_info->glyphs[i].symbol == 0))
				continue;
			error = glyph_to_bitmap(ass_instance->synth_priv,
					text_info->glyphs[i].glyph, text_info->glyphs[i].outline_glyph,
					&text_info->glyphs[i].bm, &text_info->glyphs[i].bm_o, text_info->glyphs[i].be);
			if (error)
				text_info->glyphs[i].symbol = 0;
			FT_Done_Glyph(text_info->glyphs[i].glyph);
			if (text_info->glyphs[i].outline_glyph)
				FT_Done_Glyph(text_info->glyphs[i].outline_glyph);

			// cache
			hash_val.bbox_scaled = text_info->glyphs[i].bbox;
			hash_val.bm_o = text_info->glyphs[i].bm_o;
			hash_val.bm = text_info->glyphs[i].bm;
			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') || !info->bm_o)
			continue;

		pen_x = dst_x + info->pos.x;
		pen_y = dst_y + info->pos.y;
		bm = info->bm_o;
		
		if ((info->effect_type == EF_KARAOKE_KO) && (info->effect_timing <= info->bbox.xMax)) {
			// do nothing
		} else
			tail = render_glyph(bm, pen_x, pen_y, info->c[2], 0, 1000000, tail);
	}
	for (i = 0; i < text_info->length; ++i) {
		glyph_info_t* info = text_info->glyphs + i;
		if ((info->symbol == 0) || (info->symbol == '\n') || !info->bm)
			continue;

		pen_x = dst_x + info->pos.x;
		pen_y = dst_y + info->pos.y;
		bm = info->bm;

		if ((info->effect_type == EF_KARAOKE) || (info->effect_type == EF_KARAOKE_KO)) {
			if (info->effect_timing > info->bbox.xMax)
				tail = render_glyph(bm, pen_x, pen_y, info->c[0], 0, 1000000, tail);
			else
				tail = render_glyph(bm, pen_x, pen_y, info->c[1], 0, 1000000, tail);
		} else if (info->effect_type == EF_KARAOKE_KF) {
			tail = render_glyph(bm, pen_x, pen_y, info->c[0], info->c[1], info->effect_timing, tail);
		} else
			tail = render_glyph(bm, pen_x, pen_y, info->c[0], 0, 1000000, tail);
	}

	*tail = 0;
	return head;
}

/**
 * \brief Mapping between script and screen coordinates
 */
static int x2scr(int x) {
	return x*frame_context.width / frame_context.track->PlayResX + global_settings->left_margin;
}
/**
 * \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) {
	if (global_settings->use_margins)
		return y * frame_context.orig_height / frame_context.track->PlayResY;
	else
		return y * frame_context.orig_height / frame_context.track->PlayResY + global_settings->top_margin;
}
// the same for subtitles
static int y2scr_sub(int y) {
	if (global_settings->use_margins)
		return y * frame_context.orig_height / frame_context.track->PlayResY +
		       global_settings->top_margin + global_settings->bottom_margin;
	else
		return y * frame_context.orig_height / frame_context.track->PlayResY + global_settings->top_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, const char* sample) {
	int len = strlen(sample);
	if (strncmp(*p, sample, len) == 0) {
		(*p) += len;
		return 1;
	} else
		return 0;
}

double ass_internal_font_size_coeff = 0.8;

static void change_font_size(int sz)
{
	double size = sz * frame_context.font_scale;

	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);

		if (render_context.stroker != 0) {
			FT_Stroker_Done(render_context.stroker);
			render_context.stroker = 0;
		}
#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;
		}
	}
}

/**
 * \brief Change border width
 * negative value resets border to style value
 */
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 {
		int b;
		if (border < 0) {
			if (render_context.style->BorderStyle == 1) {
				if (render_context.style->Outline == 0 && render_context.style->Shadow > 0)
					border = 1.;
				else
					border = render_context.style->Outline;
			} else
				border = 1.;
		}
		render_context.border = border;

		b = 64 * border * frame_context.border_scale;
		if (b > 0)
			FT_Stroker_Set( render_context.stroker, b,
				FT_STROKER_LINECAP_ROUND,
				FT_STROKER_LINEJOIN_ROUND,
				0 );
		else {
			FT_Stroker_Done(render_context.stroker);
			render_context.stroker = 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 Multiply two alpha values
 * \param a first value
 * \param b second value
 * \return result of multiplication
 * Parameters and result are limited by 0xFF.
 */
static uint32_t mult_alpha(uint32_t a, uint32_t b)
{
	return 0xFF - (0xFF - a) * (0xFF - b) / 0xFF;
}

/**
 * \brief Calculate alpha value by piecewise linear function
 * Used for \fad, \fade implementation.
 */
static unsigned 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;
	}

	return a;
}

static void reset_render_context();

/**
 * \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 = -1.; // reset to default
		change_border(val);
	} else if (mystrcmp(&p, "move")) {
		int x1, x2, y1, y2;
		long long t1, t2, 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);
		if (*p == ',') {
			skip(',');
			t1 = strtoll(p, &p, 10);
			skip(',');
			t2 = strtoll(p, &p, 10);
			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "movement6: (%d, %d) -> (%d, %d), (%" PRId64 " .. %" PRId64 ")\n", 
				x1, y1, x2, y2, (int64_t)t1, (int64_t)t2);
		} else {
			t1 = 0;
			t2 = render_context.event->Duration;
			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "movement: (%d, %d) -> (%d, %d)\n", x1, y1, x2, y2);
		}
		skip(')');
		delta_t = t2 - t1;
		t = frame_context.time - render_context.event->Start;
		if (t < t1)
			k = 0.;
		else if (t > t2)
			k = 1.;
		else 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")) {
		double val;
		mystrtod(&p, &val);
		mp_msg(MSGT_GLOBAL, MSGL_V, "frx/fry unimplemented \n");
	} else if (mystrcmp(&p, "frz") || mystrcmp(&p, "fr")) {
		double angle;
		double val;
		mystrtod(&p, &val);
		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;
		int i;
		if (strtocolor(&p, &val)) {
			unsigned char a = val >> 24;
			for (i = 0; i < 4; ++i)
				change_alpha(&render_context.c[i], a, pwr);
		} else {
			change_alpha(&render_context.c[0], render_context.style->PrimaryColour, pwr);
			change_alpha(&render_context.c[1], render_context.style->SecondaryColour, pwr);
			change_alpha(&render_context.c[2], render_context.style->OutlineColour, pwr);
			change_alpha(&render_context.c[3], 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, "fad")) {
		int a1, a2, a3;
		long long t1, t2, t3, t4;
		if (*p == 'e') ++p; // either \fad or \fade
		skip('(');
		a1 = strtol(p, &p, 10);
		skip(',');
		a2 = strtol(p, &p, 10);
		if (*p == ')') {
			// 2-argument version (\fad, according to specs)
			// a1 and a2 are fade-in and fade-out durations
			t1 = 0;
			t4 = render_context.event->Duration;
			t2 = a1;
			t3 = t4 - a2;
			a1 = 0xFF;
			a2 = 0;
			a3 = 0xFF;
		} else {
			// 6-argument version (\fade)
			// a1 and a2 (and a3) are opacity values
			skip(',');
			a3 = strtol(p, &p, 10);
			skip(',');
			t1 = strtoll(p, &p, 10);
			skip(',');
			t2 = strtoll(p, &p, 10);
			skip(',');
			t3 = strtoll(p, &p, 10);
			skip(',');
			t4 = strtoll(p, &p, 10);
		}
		skip(')');
		render_context.fade = interpolate_alpha(frame_context.time - render_context.event->Start, t1, t2, t3, t4, a1, a2, a3);
	} 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.c[0], val, pwr);
	} else if ((*p >= '1') && (*p <= '4') && (++p) && (mystrcmp(&p, "c") || mystrcmp(&p, "a"))) {
		char n = *(p-2);
		int cidx = n - '1';
		char cmd = *(p-1);
		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 (cmd) {
			case 'c': change_color(render_context.c + cidx, val, pwr); break;
			case 'a': change_alpha(render_context.c + cidx, 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, render_context.c[cidx]);
	} else if (mystrcmp(&p, "r")) {
		reset_render_context();
	} else if (mystrcmp(&p, "be")) {
		int val;
		if (mystrtoi(&p, 10, &val))
			render_context.be = val ? 1 : 0;
		else
			render_context.be = 0;
		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;
		if (render_context.effect_timing)
			render_context.effect_skip_timing += render_context.effect_timing;
		render_context.effect_timing = val * 10;
	} else if (mystrcmp(&p, "ko")) {
		int val = strtol(p, &p, 10);
		render_context.effect_type = EF_KARAOKE_KO;
		if (render_context.effect_timing)
			render_context.effect_skip_timing += render_context.effect_timing;
		render_context.effect_timing = val * 10;
	} else if (mystrcmp(&p, "k")) {
		int val = strtol(p, &p, 10);
		render_context.effect_type = EF_KARAOKE;
		if (render_context.effect_timing)
			render_context.effect_skip_timing += render_context.effect_timing;
		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;
}

static void apply_transition_effects(ass_event_t* event)
{
	int v[4];
	int cnt;
	char* p = event->Effect;

	if (!p || !*p) return;

	cnt = 0;
	while (cnt < 4 && (p = strchr(p, ';'))) {
		v[cnt++] = atoi(++p);
	}
	
	if (strncmp(event->Effect, "Banner;", 7) == 0) {
		int delay;
		if (cnt < 1) {
			mp_msg(MSGT_GLOBAL, MSGL_V, "Error parsing effect: %s \n", event->Effect);
			return;
		}
		if (cnt >= 2 && v[1] == 0) // right-to-left
			render_context.scroll_direction = SCROLL_RL;
		else // left-to-right
			render_context.scroll_direction = SCROLL_LR;

		delay = v[0];
		if (delay == 0) delay = 1; // ?
		render_context.scroll_shift = (frame_context.time - render_context.event->Start) / delay;
		render_context.evt_type = EVENT_HSCROLL;
		return;
	}

	if (strncmp(event->Effect, "Scroll up;", 10) == 0) {
		render_context.scroll_direction = SCROLL_BT;
	} else if (strncmp(event->Effect, "Scroll down;", 12) == 0) {
		render_context.scroll_direction = SCROLL_TB;
	} else {
		mp_msg(MSGT_GLOBAL, MSGL_V, "Unknown transition effect: %s \n", event->Effect);
		return;
	}
	// parse scroll up/down parameters
	{
		int delay;
		int y0, y1;
		if (cnt < 3) {
			mp_msg(MSGT_GLOBAL, MSGL_V, "Error parsing effect: %s \n", event->Effect);
			return;
		}
		delay = v[2];
		if (delay == 0) delay = 1; // ?
		render_context.scroll_shift = (frame_context.time - render_context.event->Start) / delay;
		if (v[0] < v[1]) {
			y0 = v[0]; y1 = v[1];
		} else {
			y0 = v[1]; y1 = v[0];
		}
		if (y1 == 0)
			y1 = frame_context.track->PlayResY; // y0=y1=0 means fullscreen scrolling
		render_context.clip_y0 = y0;
		render_context.clip_y1 = y1;
		render_context.evt_type = EVENT_VSCROLL;
		render_context.detect_collisions = 0;
	}

}

/**
 * \brief partially reset render_context to style values
 * Works like {\r}: resets some style overrides
 */
static void reset_render_context(void)
{
	render_context.c[0] = render_context.style->PrimaryColour;
	render_context.c[1] = render_context.style->SecondaryColour;
	render_context.c[2] = render_context.style->OutlineColour;
	render_context.c[3] = 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();

	change_border(-1.);
	render_context.scale_x = render_context.style->ScaleX;
	render_context.scale_y = render_context.style->ScaleY;
	render_context.hspacing = 0; // FIXME
	render_context.be = 0;

	// FIXME: does not reset unsupported attributes.
}

/**
 * \brief Start new event. Reset render_context.
 */
static void init_render_context(ass_event_t* event)
{
	render_context.event = event;
	render_context.style = frame_context.track->styles + event->Style;

	reset_render_context();

	render_context.evt_type = EVENT_NORMAL;
	render_context.alignment = 0;
	render_context.rotation = M_PI * render_context.style->Angle / 180.;
	render_context.pos_x = 0;
	render_context.pos_y = 0;
	render_context.org_x = 0;
	render_context.org_y = 0;
	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;
	render_context.fade = 0;
	render_context.effect_type = EF_NONE;
	render_context.effect_timing = 0;
	render_context.effect_skip_timing = 0;
	
	apply_transition_effects(event);
}

static void free_render_context(void)
{
	if (render_context.stroker != 0) {
		FT_Stroker_Done(render_context.stroker);
		render_context.stroker = 0;
	}
}

/**
 * \brief Get normal and outline glyphs from cache (if possible) or font face
 * \param index face glyph index
 * \param symbol ucs4 char<commit_msg>Fix FT_Stroker use in libass. The previous variant ended up with 0-width outline in some cases.<commit_after>#include "config.h"

#include <assert.h>
#include <math.h>
#include <inttypes.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_bitmap.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

static int last_render_id = 0;

struct ass_instance_s {
	FT_Library library;
	fc_instance_t* fontconfig_priv;
	ass_settings_t settings;
	int render_id;
	ass_synth_priv_t* synth_priv;

	ass_image_t* images_root; // rendering result is stored here
};

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;
	bitmap_t* bm;
	bitmap_t* bm_o;
	FT_BBox bbox;
	FT_Vector pos;
	char linebreak; // the first (leading) glyph of some line ?
	uint32_t c[4]; // colors
	FT_Vector advance; // 26.6
	effect_t effect_type;
	int effect_timing; // time duration of current karaoke word
	                   // after process_karaoke_effects: distance in pixels from the glyph origin.
	                   // part of the glyph to the left of it is displayed in a different color.
	int effect_skip_timing; // delay after the end of last karaoke word
	int asc, desc; // font max ascender and descender
//	int height;
	int be; // blur edges
	
	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
		EVENT_HSCROLL, // "Banner" transition effect, text_width is unlimited
		EVENT_VSCROLL // "Scroll up", "Scroll down" transition effects
		} 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 c[4]; // colors(Primary, Secondary, so on) in RGBA
	int clip_x0, clip_y0, clip_x1, clip_y1;
	char detect_collisions;
	uint32_t fade; // alpha from \fad
	char be; // blur edges

	effect_t effect_type;
	int effect_timing;
	int effect_skip_timing;

	enum { SCROLL_LR, // left-to-right
	       SCROLL_RL,
	       SCROLL_TB, // top-to-bottom
	       SCROLL_BT
	       } scroll_direction; // for EVENT_HSCROLL, EVENT_VSCROLL
	int scroll_shift;

	// 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 )
	int orig_width; // frame width ( = screen width - margins )
	ass_track_t* track;
	long long time; // frame's timestamp, ms
	double font_scale;
	double font_scale_x; // x scale applied to all glyphs to preserve text aspect ratio
	double border_scale;
} 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;

// a rendered event
typedef struct event_images_s {
	ass_image_t* imgs;
	int top, height;
	int detect_collisions;
	int shift_direction;
	ass_event_t* event;
} event_images_t;

struct render_priv_s {
	int top, height;
	int render_id;
};

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_width) /
			frame_context.orig_height / frame_context.width;
		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 = 0;
	
	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)
		goto ass_init_exit;
	
	error = FT_Init_FreeType( &ft );
	if ( error ) { 
		mp_msg(MSGT_GLOBAL, MSGL_FATAL, "FT_Init_FreeType failed\n");
		fontconfig_done(fc_priv);
		goto ass_init_exit;
	}

	priv = calloc(1, sizeof(ass_instance_t));
	if (!priv) {
		FT_Done_FreeType(ft);
		fontconfig_done(fc_priv);
		goto ass_init_exit;
	}

	priv->synth_priv = ass_synth_init();

	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));
	
ass_init_exit:
	if (priv) mp_msg(MSGT_GLOBAL, MSGL_INFO, "[ass] Init\n");
	else mp_msg(MSGT_GLOBAL, MSGL_ERR, "[ass] Init failed\n");

	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 && priv->synth_priv) ass_synth_done(priv->synth_priv);
	if (priv) free(priv);
	if (text_info.glyphs) free(text_info.glyphs);
}

/**
 * \brief Create a new ass_image_t
 * Parameters are the same as ass_image_t fields.
 */
static ass_image_t* my_draw_bitmap(unsigned char* bitmap, int bitmap_w, int bitmap_h, int stride, int dst_x, int dst_y, uint32_t color)
{
	ass_image_t* img = calloc(1, sizeof(ass_image_t));
	
	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;

	return img;
}

/**
 * \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
 * \param tail pointer to the last image's next field, head of the generated list should be stored here
 * \return pointer to the new list tail
 * Performs clipping. Uses my_draw_bitmap for actual bitmap convertion.
 */
static ass_image_t** render_glyph(bitmap_t* bm, int dst_x, int dst_y, uint32_t color, uint32_t color2, int brk, ass_image_t** tail)
{
	// 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;
	ass_image_t* img;

	dst_x += bm->left;
	dst_y += bm->top;
	brk -= bm->left;
	
	// 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 = bm->w;
	b_y1 = bm->h;
	
	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 - bm->w;
	if (tmp < 0) {
		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip right\n");
		b_x1 = bm->w + tmp;
	}
	tmp = clip_y1 - dst_y - bm->h;
	if (tmp < 0) {
		mp_msg(MSGT_GLOBAL, MSGL_DBG2, "clip bottom\n");
		b_y1 = bm->h + tmp;
	}
	
	if ((b_y0 >= b_y1) || (b_x0 >= b_x1))
		return tail;

	if (brk > b_x0) { // draw left part
		if (brk > b_x1) brk = b_x1;
		img = my_draw_bitmap(bm->buffer + bm->w * b_y0 + b_x0, 
			brk - b_x0, b_y1 - b_y0, bm->w,
			dst_x + b_x0, dst_y + b_y0, color);
		*tail = img;
		tail = &img->next;
	}
	if (brk < b_x1) { // draw right part
		if (brk < b_x0) brk = b_x0;
		img = my_draw_bitmap(bm->buffer + bm->w * b_y0 + brk, 
			b_x1 - brk, b_y1 - b_y0, bm->w,
			dst_x + brk, dst_y + b_y0, color2);
		*tail = img;
		tail = &img->next;
	}
	return tail;
}

/**
 * \brief Render text_info_t struct into ass_images_t list
 * Rasterize glyphs and put them in glyph cache.
 */
static ass_image_t* render_text(text_info_t* text_info, int dst_x, int dst_y)
{
	int pen_x, pen_y;
	int i, error;
	bitmap_t* bm;
	glyph_hash_val_t hash_val;
	ass_image_t* head;
	ass_image_t** tail = &head;

	for (i = 0; i < text_info->length; ++i) {
		if (text_info->glyphs[i].glyph) {
			if ((text_info->glyphs[i].symbol == '\n') || (text_info->glyphs[i].symbol == 0))
				continue;
			error = glyph_to_bitmap(ass_instance->synth_priv,
					text_info->glyphs[i].glyph, text_info->glyphs[i].outline_glyph,
					&text_info->glyphs[i].bm, &text_info->glyphs[i].bm_o, text_info->glyphs[i].be);
			if (error)
				text_info->glyphs[i].symbol = 0;
			FT_Done_Glyph(text_info->glyphs[i].glyph);
			if (text_info->glyphs[i].outline_glyph)
				FT_Done_Glyph(text_info->glyphs[i].outline_glyph);

			// cache
			hash_val.bbox_scaled = text_info->glyphs[i].bbox;
			hash_val.bm_o = text_info->glyphs[i].bm_o;
			hash_val.bm = text_info->glyphs[i].bm;
			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') || !info->bm_o)
			continue;

		pen_x = dst_x + info->pos.x;
		pen_y = dst_y + info->pos.y;
		bm = info->bm_o;
		
		if ((info->effect_type == EF_KARAOKE_KO) && (info->effect_timing <= info->bbox.xMax)) {
			// do nothing
		} else
			tail = render_glyph(bm, pen_x, pen_y, info->c[2], 0, 1000000, tail);
	}
	for (i = 0; i < text_info->length; ++i) {
		glyph_info_t* info = text_info->glyphs + i;
		if ((info->symbol == 0) || (info->symbol == '\n') || !info->bm)
			continue;

		pen_x = dst_x + info->pos.x;
		pen_y = dst_y + info->pos.y;
		bm = info->bm;

		if ((info->effect_type == EF_KARAOKE) || (info->effect_type == EF_KARAOKE_KO)) {
			if (info->effect_timing > info->bbox.xMax)
				tail = render_glyph(bm, pen_x, pen_y, info->c[0], 0, 1000000, tail);
			else
				tail = render_glyph(bm, pen_x, pen_y, info->c[1], 0, 1000000, tail);
		} else if (info->effect_type == EF_KARAOKE_KF) {
			tail = render_glyph(bm, pen_x, pen_y, info->c[0], info->c[1], info->effect_timing, tail);
		} else
			tail = render_glyph(bm, pen_x, pen_y, info->c[0], 0, 1000000, tail);
	}

	*tail = 0;
	return head;
}

/**
 * \brief Mapping between script and screen coordinates
 */
static int x2scr(int x) {
	return x*frame_context.width / frame_context.track->PlayResX + global_settings->left_margin;
}
/**
 * \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) {
	if (global_settings->use_margins)
		return y * frame_context.orig_height / frame_context.track->PlayResY;
	else
		return y * frame_context.orig_height / frame_context.track->PlayResY + global_settings->top_margin;
}
// the same for subtitles
static int y2scr_sub(int y) {
	if (global_settings->use_margins)
		return y * frame_context.orig_height / frame_context.track->PlayResY +
		       global_settings->top_margin + global_settings->bottom_margin;
	else
		return y * frame_context.orig_height / frame_context.track->PlayResY + global_settings->top_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, const char* sample) {
	int len = strlen(sample);
	if (strncmp(*p, sample, len) == 0) {
		(*p) += len;
		return 1;
	} else
		return 0;
}

double ass_internal_font_size_coeff = 0.8;

static void change_font_size(int sz)
{
	double size = sz * frame_context.font_scale;

	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
 * negative value resets border to style value
 */
static void change_border(double border)
{
	int b;
	if (!render_context.face) return;

		if (border < 0) {
			if (render_context.style->BorderStyle == 1) {
				if (render_context.style->Outline == 0 && render_context.style->Shadow > 0)
					border = 1.;
				else
					border = render_context.style->Outline;
			} else
				border = 1.;
		}
		render_context.border = border;

		b = 64 * border * frame_context.border_scale;
		if (b > 0) {
		if (!render_context.stroker) {
			int error;
#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;
			}
		}
		if (render_context.stroker)
			FT_Stroker_Set( render_context.stroker, b,
				FT_STROKER_LINECAP_ROUND,
				FT_STROKER_LINEJOIN_ROUND,
				0 );
		} else {
			FT_Stroker_Done(render_context.stroker);
			render_context.stroker = 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 Multiply two alpha values
 * \param a first value
 * \param b second value
 * \return result of multiplication
 * Parameters and result are limited by 0xFF.
 */
static uint32_t mult_alpha(uint32_t a, uint32_t b)
{
	return 0xFF - (0xFF - a) * (0xFF - b) / 0xFF;
}

/**
 * \brief Calculate alpha value by piecewise linear function
 * Used for \fad, \fade implementation.
 */
static unsigned 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;
	}

	return a;
}

static void reset_render_context();

/**
 * \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 = -1.; // reset to default
		change_border(val);
	} else if (mystrcmp(&p, "move")) {
		int x1, x2, y1, y2;
		long long t1, t2, 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);
		if (*p == ',') {
			skip(',');
			t1 = strtoll(p, &p, 10);
			skip(',');
			t2 = strtoll(p, &p, 10);
			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "movement6: (%d, %d) -> (%d, %d), (%" PRId64 " .. %" PRId64 ")\n", 
				x1, y1, x2, y2, (int64_t)t1, (int64_t)t2);
		} else {
			t1 = 0;
			t2 = render_context.event->Duration;
			mp_msg(MSGT_GLOBAL, MSGL_DBG2, "movement: (%d, %d) -> (%d, %d)\n", x1, y1, x2, y2);
		}
		skip(')');
		delta_t = t2 - t1;
		t = frame_context.time - render_context.event->Start;
		if (t < t1)
			k = 0.;
		else if (t > t2)
			k = 1.;
		else 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")) {
		double val;
		mystrtod(&p, &val);
		mp_msg(MSGT_GLOBAL, MSGL_V, "frx/fry unimplemented \n");
	} else if (mystrcmp(&p, "frz") || mystrcmp(&p, "fr")) {
		double angle;
		double val;
		mystrtod(&p, &val);
		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;
		int i;
		if (strtocolor(&p, &val)) {
			unsigned char a = val >> 24;
			for (i = 0; i < 4; ++i)
				change_alpha(&render_context.c[i], a, pwr);
		} else {
			change_alpha(&render_context.c[0], render_context.style->PrimaryColour, pwr);
			change_alpha(&render_context.c[1], render_context.style->SecondaryColour, pwr);
			change_alpha(&render_context.c[2], render_context.style->OutlineColour, pwr);
			change_alpha(&render_context.c[3], 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, "fad")) {
		int a1, a2, a3;
		long long t1, t2, t3, t4;
		if (*p == 'e') ++p; // either \fad or \fade
		skip('(');
		a1 = strtol(p, &p, 10);
		skip(',');
		a2 = strtol(p, &p, 10);
		if (*p == ')') {
			// 2-argument version (\fad, according to specs)
			// a1 and a2 are fade-in and fade-out durations
			t1 = 0;
			t4 = render_context.event->Duration;
			t2 = a1;
			t3 = t4 - a2;
			a1 = 0xFF;
			a2 = 0;
			a3 = 0xFF;
		} else {
			// 6-argument version (\fade)
			// a1 and a2 (and a3) are opacity values
			skip(',');
			a3 = strtol(p, &p, 10);
			skip(',');
			t1 = strtoll(p, &p, 10);
			skip(',');
			t2 = strtoll(p, &p, 10);
			skip(',');
			t3 = strtoll(p, &p, 10);
			skip(',');
			t4 = strtoll(p, &p, 10);
		}
		skip(')');
		render_context.fade = interpolate_alpha(frame_context.time - render_context.event->Start, t1, t2, t3, t4, a1, a2, a3);
	} 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.c[0], val, pwr);
	} else if ((*p >= '1') && (*p <= '4') && (++p) && (mystrcmp(&p, "c") || mystrcmp(&p, "a"))) {
		char n = *(p-2);
		int cidx = n - '1';
		char cmd = *(p-1);
		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 (cmd) {
			case 'c': change_color(render_context.c + cidx, val, pwr); break;
			case 'a': change_alpha(render_context.c + cidx, 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, render_context.c[cidx]);
	} else if (mystrcmp(&p, "r")) {
		reset_render_context();
	} else if (mystrcmp(&p, "be")) {
		int val;
		if (mystrtoi(&p, 10, &val))
			render_context.be = val ? 1 : 0;
		else
			render_context.be = 0;
		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;
		if (render_context.effect_timing)
			render_context.effect_skip_timing += render_context.effect_timing;
		render_context.effect_timing = val * 10;
	} else if (mystrcmp(&p, "ko")) {
		int val = strtol(p, &p, 10);
		render_context.effect_type = EF_KARAOKE_KO;
		if (render_context.effect_timing)
			render_context.effect_skip_timing += render_context.effect_timing;
		render_context.effect_timing = val * 10;
	} else if (mystrcmp(&p, "k")) {
		int val = strtol(p, &p, 10);
		render_context.effect_type = EF_KARAOKE;
		if (render_context.effect_timing)
			render_context.effect_skip_timing += render_context.effect_timing;
		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;
}

static void apply_transition_effects(ass_event_t* event)
{
	int v[4];
	int cnt;
	char* p = event->Effect;

	if (!p || !*p) return;

	cnt = 0;
	while (cnt < 4 && (p = strchr(p, ';'))) {
		v[cnt++] = atoi(++p);
	}
	
	if (strncmp(event->Effect, "Banner;", 7) == 0) {
		int delay;
		if (cnt < 1) {
			mp_msg(MSGT_GLOBAL, MSGL_V, "Error parsing effect: %s \n", event->Effect);
			return;
		}
		if (cnt >= 2 && v[1] == 0) // right-to-left
			render_context.scroll_direction = SCROLL_RL;
		else // left-to-right
			render_context.scroll_direction = SCROLL_LR;

		delay = v[0];
		if (delay == 0) delay = 1; // ?
		render_context.scroll_shift = (frame_context.time - render_context.event->Start) / delay;
		render_context.evt_type = EVENT_HSCROLL;
		return;
	}

	if (strncmp(event->Effect, "Scroll up;", 10) == 0) {
		render_context.scroll_direction = SCROLL_BT;
	} else if (strncmp(event->Effect, "Scroll down;", 12) == 0) {
		render_context.scroll_direction = SCROLL_TB;
	} else {
		mp_msg(MSGT_GLOBAL, MSGL_V, "Unknown transition effect: %s \n", event->Effect);
		return;
	}
	// parse scroll up/down parameters
	{
		int delay;
		int y0, y1;
		if (cnt < 3) {
			mp_msg(MSGT_GLOBAL, MSGL_V, "Error parsing effect: %s \n", event->Effect);
			return;
		}
		delay = v[2];
		if (delay == 0) delay = 1; // ?
		render_context.scroll_shift = (frame_context.time - render_context.event->Start) / delay;
		if (v[0] < v[1]) {
			y0 = v[0]; y1 = v[1];
		} else {
			y0 = v[1]; y1 = v[0];
		}
		if (y1 == 0)
			y1 = frame_context.track->PlayResY; // y0=y1=0 means fullscreen scrolling
		render_context.clip_y0 = y0;
		render_context.clip_y1 = y1;
		render_context.evt_type = EVENT_VSCROLL;
		render_context.detect_collisions = 0;
	}

}

/**
 * \brief partially reset render_context to style values
 * Works like {\r}: resets some style overrides
 */
static void reset_render_context(void)
{
	render_context.c[0] = render_context.style->PrimaryColour;
	render_context.c[1] = render_context.style->SecondaryColour;
	render_context.c[2] = render_context.style->OutlineColour;
	render_context.c[3] = 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();

	change_border(-1.);
	render_context.scale_x = render_context.style->ScaleX;
	render_context.scale_y = render_context.style->ScaleY;
	render_context.hspacing = 0; // FIXME
	render_context.be = 0;

	// FIXME: does not reset unsupported attributes.
}

/**
 * \brief Start new event. Reset render_context.
 */
static void init_render_context(ass_event_t* event)
{
	render_context.event = event;
	render_context.style = frame_context.track->styles + event->Style;

	reset_render_context();

	render_context.evt_type = EVENT_NORMAL;
	render_context.alignment = 0;
	render_context.rotation = M_PI * render_context.style->Angle / 180.;
	render_context.pos_x = 0;
	render_context.pos_y = 0;
	render_context.org_x = 0;
	render_context.org_y = 0;
	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;
	render_context.fade = 0;
	render_context.effect_type = EF_NONE;
	render_context.effect_timing = 0;
	render_context.effect_skip_timing = 0;
	
	apply_transition_effects(event);
}

static void free_render_context(void)
{
}

/**
 * \brief Get normal and outline glyphs from cache (if possible) or font face
 * \param index face glyph index
 * \param symbol ucs4 char
{'fraction_non_alphanumeric': 0.15771339545195792, 'fraction_numerical': 0.02155676064355694, 'mean_word_length': 3.563820332262255, 'pattern_counts': {'":': 0, '<': 95, '<?xml version=': 0, '>': 447, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2181873', 'n_tokens_mistral': 29869, 'n_tokens_neox': 27148, 'n_words': 6610}