Remove unnecessary CWord.Copy calls.
[xy_vsfilter.git] / src / subtitles / RTS.cpp
blobdbb257dbb64f3446b9825609a42a750ca0fb2b8d
1 /*
2 * Copyright (C) 2003-2006 Gabest
3 * http://www.gabest.org
5 * This Program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
8 * any later version.
10 * This Program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with GNU Make; see the file COPYING. If not, write to
17 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 #include "stdafx.h"
23 #include <math.h>
24 #include <time.h>
25 #include "RTS.h"
26 #include "cache_manager.h"
27 #include "../subpic/color_conv_table.h"
28 #include "subpixel_position_controler.h"
30 // WARNING: this isn't very thread safe, use only one RTS a time.
31 static HDC g_hDC;
32 static int g_hDC_refcnt = 0;
34 enum XY_MSP_SUBTYPE {XY_AYUV, XY_AUYV};
35 static inline DWORD rgb2yuv(DWORD argb, XY_MSP_SUBTYPE type)
37 const ColorConvTable* color_conv_table = ColorConvTable::GetDefaultColorConvTable();
38 DWORD axxv;
39 int r = (argb & 0x00ff0000) >> 16;
40 int g = (argb & 0x0000ff00) >> 8;
41 int b = (argb & 0x000000ff);
42 int y = (color_conv_table->c2y_cyb * b + color_conv_table->c2y_cyg * g + color_conv_table->c2y_cyr * r + 0x108000) >> 16;
43 int scaled_y = (y-16) * color_conv_table->cy_cy;
44 int u = ((((b<<16) - scaled_y) >> 10) * color_conv_table->c2y_cu + 0x800000 + 0x8000) >> 16;
45 int v = ((((r<<16) - scaled_y) >> 10) * color_conv_table->c2y_cv + 0x800000 + 0x8000) >> 16;
46 DbgLog((LOG_TRACE, 5, TEXT("argb=%x r=%d %x g=%d %x b=%d %x y=%d %x u=%d %x v=%d %x"), argb, r, r, g, g, b, b, y, y, u, u, v, v));
47 u *= (u>0);
48 u = 255 - (255-u)*(u<256);
49 v *= (v>0);
50 v = 255 - (255-v)*(v<256);
51 DbgLog((LOG_TRACE, 5, TEXT("u=%x v=%x"), u, v));
52 if(type==XY_AYUV)
53 axxv = (argb & 0xff000000) | (y<<16) | (u<<8) | v;
54 else
55 axxv = (argb & 0xff000000) | (y<<8) | (u<<16) | v;
56 DbgLog((LOG_TRACE, 5, TEXT("axxv=%x"), axxv));
57 return axxv;
58 //return argb;
60 static long revcolor(long c)
62 return ((c&0xff0000)>>16) + (c&0xff00) + ((c&0xff)<<16);
65 // Skip all leading whitespace
66 inline CStringW::PCXSTR SkipWhiteSpaceLeft(const CStringW& str)
68 CStringW::PCXSTR psz = str.GetString();
70 while( iswspace( *psz ) )
72 psz++;
74 return psz;
77 // Skip all trailing whitespace
78 inline CStringW::PCXSTR SkipWhiteSpaceRight(const CStringW& str)
80 CStringW::PCXSTR psz = str.GetString();
81 CStringW::PCXSTR pszLast = psz + str.GetLength() - 1;
82 bool first_white = false;
83 while( iswspace( *pszLast ) )
85 pszLast--;
86 if(pszLast<psz)
87 break;
89 return pszLast;
92 // Skip all leading whitespace
93 inline CStringW::PCXSTR SkipWhiteSpaceLeft(CStringW::PCXSTR start, CStringW::PCXSTR end)
95 while( start!=end && iswspace( *start ) )
97 start++;
99 return start;
102 // Skip all trailing whitespace, first char must NOT be white space
103 inline CStringW::PCXSTR FastSkipWhiteSpaceRight(CStringW::PCXSTR start, CStringW::PCXSTR end)
105 while( iswspace( *--end ) );
106 return end+1;
109 inline CStringW::PCXSTR FindChar(CStringW::PCXSTR start, CStringW::PCXSTR end, WCHAR c)
111 while( start!=end && *start!=c )
113 start++;
115 return start;
118 //////////////////////////////////////////////////////////////////////////////////////////////
120 // CMyFont
122 CMyFont::CMyFont(const STSStyleBase& style)
124 LOGFONT lf;
125 memset(&lf, 0, sizeof(lf));
126 lf <<= style;
127 lf.lfHeight = (LONG)(style.fontSize+0.5);
128 lf.lfOutPrecision = OUT_TT_PRECIS;
129 lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
130 lf.lfQuality = ANTIALIASED_QUALITY;
131 lf.lfPitchAndFamily = DEFAULT_PITCH|FF_DONTCARE;
132 if(!CreateFontIndirect(&lf))
134 _tcscpy(lf.lfFaceName, _T("Arial"));
135 CreateFontIndirect(&lf);
137 HFONT hOldFont = SelectFont(g_hDC, *this);
138 TEXTMETRIC tm;
139 GetTextMetrics(g_hDC, &tm);
140 m_ascent = ((tm.tmAscent + 4) >> 3);
141 m_descent = ((tm.tmDescent + 4) >> 3);
142 SelectFont(g_hDC, hOldFont);
145 // CWord
147 CWord::CWord(const FwSTSStyle& style, const CStringW& str, int ktype, int kstart, int kend)
148 : m_style(style), m_str(str)
149 , m_width(0), m_ascent(0), m_descent(0)
150 , m_ktype(ktype), m_kstart(kstart), m_kend(kend)
151 , m_fLineBreak(false), m_fWhiteSpaceChar(false)
152 //, m_pOpaqueBox(NULL)
154 if(m_str.IsEmpty())
156 m_fWhiteSpaceChar = m_fLineBreak = true;
158 FwCMyFont font( static_cast<const STSStyleBase&>(m_style.get()) );
159 m_ascent = (int)(m_style.get().fontScaleY/100*font.get().m_ascent);
160 m_descent = (int)(m_style.get().fontScaleY/100*font.get().m_descent);
161 m_width = 0;
164 CWord::CWord( const CWord& src)
166 m_str = src.m_str;
167 m_fWhiteSpaceChar = src.m_fWhiteSpaceChar;
168 m_fLineBreak = src.m_fLineBreak;
169 m_style = src.m_style;
170 m_pOpaqueBox = src.m_pOpaqueBox;//allow since it is shared_ptr
171 m_ktype = src.m_ktype;
172 m_kstart = src.m_kstart;
173 m_kend = src.m_kend;
174 m_width = src.m_width;
175 m_ascent = src.m_ascent;
176 m_descent = src.m_descent;
179 CWord::~CWord()
181 //if(m_pOpaqueBox) delete m_pOpaqueBox;
184 bool CWord::Append(const SharedPtrCWord& w)
186 if(!(m_style == w->m_style)
187 || m_fLineBreak || w->m_fLineBreak
188 || w->m_kstart != w->m_kend || m_ktype != w->m_ktype) return(false);
189 m_fWhiteSpaceChar = m_fWhiteSpaceChar && w->m_fWhiteSpaceChar;
190 m_str += w->m_str;
191 m_width += w->m_width;
192 return(true);
195 void CWord::Paint( SharedPtrCWord word, const CPoint& p, const CPoint& org, OverlayList* overlay_list )
197 if(!word->m_str || overlay_list==NULL) return;
199 CPoint trans_org = org - p;
200 bool need_transform = word->NeedTransform();
201 if(!need_transform)
203 trans_org.x=0;
204 trans_org.y=0;
207 if( SubpixelPositionControler::GetGlobalControler().UseBilinearShift() )
209 CPoint psub_true( (p.x&SubpixelPositionControler::EIGHT_X_EIGHT_MASK), (p.y&SubpixelPositionControler::EIGHT_X_EIGHT_MASK) );
210 OverlayKey sub_key(*word, psub_true, trans_org);
212 OverlayMruCache* overlay_cache = CacheManager::GetSubpixelVarianceCache();
214 OverlayMruCache::hashed_cache_const_iterator iter = overlay_cache->hash_find(sub_key);
215 if(iter!=overlay_cache->hash_end())
217 overlay_list->overlay = iter->overlay;
218 overlay_cache->update_cache( *iter );
221 if( !overlay_list->overlay )
223 CPoint psub = SubpixelPositionControler::GetGlobalControler().GetSubpixel(p);
224 OverlayKey overlay_key(*word, psub, trans_org);
225 OverlayMruCache* overlay_cache = CacheManager::GetOverlayMruCache();
226 OverlayMruCache::hashed_cache_const_iterator iter = overlay_cache->hash_find(overlay_key);
227 if(iter==overlay_cache->hash_end())
229 word->DoPaint(psub, trans_org, &(overlay_list->overlay), overlay_key);
230 OverlayMruItem item(overlay_key, overlay_list->overlay);
231 overlay_cache->update_cache(item);
233 else
235 overlay_list->overlay = iter->overlay;
236 overlay_cache->update_cache( *iter );
238 if( SubpixelPositionControler::GetGlobalControler().UseBilinearShift()
239 && (psub.x!=(p.x&SubpixelPositionControler::EIGHT_X_EIGHT_MASK)
240 || psub.y!=(p.y&SubpixelPositionControler::EIGHT_X_EIGHT_MASK)) )
242 overlay_list->overlay.reset(overlay_list->overlay->GetSubpixelVariance((p.x&SubpixelPositionControler::EIGHT_X_EIGHT_MASK) - psub.x,
243 (p.y&SubpixelPositionControler::EIGHT_X_EIGHT_MASK) - psub.y));
244 CPoint psub_true( (p.x&SubpixelPositionControler::EIGHT_X_EIGHT_MASK), (p.y&SubpixelPositionControler::EIGHT_X_EIGHT_MASK) );
245 OverlayKey sub_key(*word, psub_true, trans_org);
246 OverlayMruCache* overlay_cache = CacheManager::GetSubpixelVarianceCache();
247 OverlayMruItem item(sub_key, overlay_list->overlay);
248 overlay_cache->update_cache(item);
252 if(word->m_style.get().borderStyle == 1)
254 if(!word->CreateOpaqueBox()) return;
255 overlay_list->next = new OverlayList();
256 Paint(word->m_pOpaqueBox, p, org, overlay_list->next);
260 void CWord::DoPaint(const CPoint& psub, const CPoint& trans_org, SharedPtrOverlay* overlay, const OverlayKey& key)
262 overlay->reset(new Overlay());
264 OverlayNoBlurMruCache* overlay_no_blur_cache = CacheManager::GetOverlayNoBlurMruCache();
265 OverlayNoBlurMruCache::hashed_cache_const_iterator iter = overlay_no_blur_cache->hash_find(key);
267 SharedPtrOverlay raterize_result;
268 if(iter==overlay_no_blur_cache->hash_end())
270 raterize_result.reset(new Overlay());
272 SharedPtrConstScanLineData scan_line_data;
273 ScanLineDataMruCache* scan_line_data_cache = CacheManager::GetScanLineDataMruCache();
274 ScanLineDataMruCache::hashed_cache_const_iterator iter = scan_line_data_cache->hash_find(key);
275 if(iter==scan_line_data_cache->hash_end())
277 //get outline path, if not cached, create it and cache a copy, else copy from cache
278 SharedPtrPathData path_data(new PathData());
279 PathDataMruCache* path_data_cache = CacheManager::GetPathDataMruCache();
280 PathDataMruCache::hashed_cache_const_iterator iter = path_data_cache->hash_find(key);
281 if(iter==path_data_cache->hash_end())
283 if(!CreatePath(path_data)) return;
285 SharedPtrPathData data(new PathData());
286 *data = *path_data;//important! copy not ref
287 PathDataMruItem item(key, data);
288 path_data_cache->update_cache(item);
290 else
292 *path_data = *(iter->path_data); //important! copy not ref
293 path_data_cache->update_cache( *iter );
296 bool need_transform = NeedTransform();
297 if(need_transform)
298 Transform(path_data, CPoint(trans_org.x*8, trans_org.y*8));
300 SharedPtrScanLineData tmp(new ScanLineData());
301 if(!tmp->ScanConvert(path_data)) return;
302 if(m_style.get().borderStyle == 0 && (m_style.get().outlineWidthX+m_style.get().outlineWidthY > 0))
304 if(!tmp->CreateWidenedRegion((int)(m_style.get().outlineWidthX+0.5), (int)(m_style.get().outlineWidthY+0.5))) return;
306 else if(m_style.get().borderStyle == 1)
308 if(!CreateOpaqueBox()) return;
311 ScanLineDataMruItem item(key, tmp);
312 scan_line_data_cache->update_cache(item);
313 scan_line_data = tmp;
315 else
317 scan_line_data = iter->scan_line_data;
318 scan_line_data_cache->update_cache( *iter );
320 if(!Rasterizer::Rasterize(*scan_line_data, psub.x, psub.y, raterize_result)) return;
322 OverlayNoBlurMruItem item(key, raterize_result);
323 overlay_no_blur_cache->update_cache(item);
325 else
327 raterize_result = iter->overlay;
328 overlay_no_blur_cache->update_cache( *iter );
330 if(!Rasterizer::Blur(*raterize_result, m_style.get().fBlur, m_style.get().fGaussianBlur, *overlay))
332 *overlay = raterize_result;
336 bool CWord::NeedTransform()
338 return (fabs(m_style.get().fontScaleX - 100) > 0.000001) ||
339 (fabs(m_style.get().fontScaleY - 100) > 0.000001) ||
340 (fabs(m_style.get().fontAngleX) > 0.000001) ||
341 (fabs(m_style.get().fontAngleY) > 0.000001) ||
342 (fabs(m_style.get().fontAngleZ) > 0.000001) ||
343 (fabs(m_style.get().fontShiftX) > 0.000001) ||
344 (fabs(m_style.get().fontShiftY) > 0.000001);
347 void CWord::Transform(SharedPtrPathData path_data, const CPoint& org)
349 // CPUID from VDub
350 bool fSSE2 = !!(g_cpuid.m_flags & CCpuID::sse2);
352 if(fSSE2) { // SSE code
353 Transform_SSE2(path_data, org);
354 } else // C-code
355 Transform_C(path_data, org);
358 void CWord::Transform_C(const SharedPtrPathData& path_data, const CPoint &org )
360 double scalex = m_style.get().fontScaleX/100;
361 double scaley = m_style.get().fontScaleY/100;
363 double caz = cos((3.1415/180)*m_style.get().fontAngleZ);
364 double saz = sin((3.1415/180)*m_style.get().fontAngleZ);
365 double cax = cos((3.1415/180)*m_style.get().fontAngleX);
366 double sax = sin((3.1415/180)*m_style.get().fontAngleX);
367 double cay = cos((3.1415/180)*m_style.get().fontAngleY);
368 double say = sin((3.1415/180)*m_style.get().fontAngleY);
370 #ifdef _VSMOD
371 // patch m003. random text points
372 double xrnd = m_style.get().mod_rand.X*100;
373 double yrnd = m_style.get().mod_rand.Y*100;
374 double zrnd = m_style.get().mod_rand.Z*100;
376 srand(m_style.get().mod_rand.Seed);
378 // patch m008. distort
379 int xsz,ysz;
380 double dst1x,dst1y,dst2x,dst2y,dst3x,dst3y;
381 int minx = INT_MAX, miny = INT_MAX, maxx = -INT_MAX, maxy = -INT_MAX;
383 bool is_dist = m_style.get().mod_distort.enabled;
384 if (is_dist) {
385 for(int i = 0; i < path_data->mPathPoints; i++) {
386 if(minx > path_data->mpPathPoints[i].x) {
387 minx = path_data->mpPathPoints[i].x;
389 if(miny > path_data->mpPathPoints[i].y) {
390 miny = path_data->mpPathPoints[i].y;
392 if(maxx < path_data->mpPathPoints[i].x) {
393 maxx = path_data->mpPathPoints[i].x;
395 if(maxy < path_data->mpPathPoints[i].y) {
396 maxy = path_data->mpPathPoints[i].y;
400 xsz = max(maxx - minx, 0);
401 ysz = max(maxy - miny, 0);
403 dst1x = m_style.get().mod_distort.pointsx[0];
404 dst1y = m_style.get().mod_distort.pointsy[0];
405 dst2x = m_style.get().mod_distort.pointsx[1];
406 dst2y = m_style.get().mod_distort.pointsy[1];
407 dst3x = m_style.get().mod_distort.pointsx[2];
408 dst3y = m_style.get().mod_distort.pointsy[2];
410 #endif
412 for (int i = 0; i < path_data->mPathPoints; i++) {
413 double x, y, z, xx, yy, zz;
415 x = path_data->mpPathPoints[i].x;
416 y = path_data->mpPathPoints[i].y;
417 #ifdef _VSMOD
418 // patch m002. Z-coord
419 z = m_style.get().mod_z;
421 double u, v;
422 if (is_dist) {
423 u = (x-minx) / xsz;
424 v = (y-miny) / ysz;
426 x = minx+(0 + (dst1x - 0)*u + (dst3x-0)*v+(0+dst2x-dst1x-dst3x)*u*v)*xsz;
427 y = miny+(0 + (dst1y - 0)*u + (dst3y-0)*v+(0+dst2y-dst1y-dst3y)*u*v)*ysz;
428 //P = P0 + (P1 - P0)u + (P3 - P0)v + (P0 + P2 - P1 - P3)uv
431 // patch m003. random text points
432 x = xrnd > 0 ? (xrnd - rand() % (int)(xrnd * 2 + 1)) / 100.0 + x : x;
433 y = yrnd > 0 ? (yrnd - rand() % (int)(yrnd * 2 + 1)) / 100.0 + y : y;
434 z = zrnd > 0 ? (zrnd - rand() % (int)(zrnd * 2 + 1)) / 100.0 + z : z;
435 #else
436 z = 0;
437 #endif
438 double _x = x;
439 x = scalex * (x + m_style.get().fontShiftX * y) - org.x;
440 y = scaley * (y + m_style.get().fontShiftY * _x) - org.y;
442 xx = x*caz + y*saz;
443 yy = -(x*saz - y*caz);
444 zz = z;
446 x = xx;
447 y = yy*cax + zz*sax;
448 z = yy*sax - zz*cax;
450 xx = x*cay + z*say;
451 yy = y;
452 zz = x*say - z*cay;
454 zz = max(zz, -19000);
456 x = (xx * 20000) / (zz + 20000);
457 y = (yy * 20000) / (zz + 20000);
459 path_data->mpPathPoints[i].x = (LONG)(x + org.x + 0.5);
460 path_data->mpPathPoints[i].y = (LONG)(y + org.y + 0.5);
464 void CWord::Transform_SSE2(const SharedPtrPathData& path_data, const CPoint &org )
466 // __m128 union data type currently not supported with Intel C++ Compiler, so just call C version
467 #ifdef __ICL
468 Transform_C(org);
469 #else
470 // SSE code
471 // speed up ~1.5-1.7x
472 double scalex = m_style.get().fontScaleX/100;
473 double scaley = m_style.get().fontScaleY/100;
475 double caz = cos((3.1415/180)*m_style.get().fontAngleZ);
476 double saz = sin((3.1415/180)*m_style.get().fontAngleZ);
477 double cax = cos((3.1415/180)*m_style.get().fontAngleX);
478 double sax = sin((3.1415/180)*m_style.get().fontAngleX);
479 double cay = cos((3.1415/180)*m_style.get().fontAngleY);
480 double say = sin((3.1415/180)*m_style.get().fontAngleY);
482 __m128 __xshift = _mm_set_ps1(m_style.get().fontShiftX);
483 __m128 __yshift = _mm_set_ps1(m_style.get().fontShiftY);
485 __m128 __xorg = _mm_set_ps1(org.x);
486 __m128 __yorg = _mm_set_ps1(org.y);
488 __m128 __xscale = _mm_set_ps1(scalex);
489 __m128 __yscale = _mm_set_ps1(scaley);
491 #ifdef _VSMOD
492 // patch m003. random text points
493 double xrnd = m_style.get().mod_rand.X*100;
494 double yrnd = m_style.get().mod_rand.Y*100;
495 double zrnd = m_style.get().mod_rand.Z*100;
497 srand(m_style.get().mod_rand.Seed);
499 __m128 __xsz = _mm_setzero_ps();
500 __m128 __ysz = _mm_setzero_ps();
502 __m128 __dst1x, __dst1y, __dst213x, __dst213y, __dst3x, __dst3y;
504 __m128 __miny;
505 __m128 __minx = _mm_set_ps(INT_MAX, INT_MAX, 0, 0);
506 __m128 __max = _mm_set_ps(-INT_MAX, -INT_MAX, 1, 1);
508 bool is_dist = m_style.get().mod_distort.enabled;
509 if(is_dist) {
510 for(int i = 0; i < path_data->mPathPoints; i++) {
511 __m128 __point = _mm_set_ps(path_data->mpPathPoints[i].x, path_data->mpPathPoints[i].y, 0, 0);
512 __minx = _mm_min_ps(__minx, __point);
513 __max = _mm_max_ps(__max, __point);
516 __m128 __zero = _mm_setzero_ps();
517 __max = _mm_sub_ps(__max, __minx); // xsz, ysz, 1, 1
518 __max = _mm_max_ps(__max, __zero);
520 __xsz = _mm_shuffle_ps(__max, __max, _MM_SHUFFLE(3,3,3,3));
521 __ysz = _mm_shuffle_ps(__max, __max, _MM_SHUFFLE(2,2,2,2));
523 __miny = _mm_shuffle_ps(__minx, __minx, _MM_SHUFFLE(2,2,2,2));
524 __minx = _mm_shuffle_ps(__minx, __minx, _MM_SHUFFLE(3,3,3,3));
526 __dst1x = _mm_set_ps1(m_style.get().mod_distort.pointsx[0]);
527 __dst1y = _mm_set_ps1(m_style.get().mod_distort.pointsy[0]);
528 __dst3x = _mm_set_ps1(m_style.get().mod_distort.pointsx[2]);
529 __dst3y = _mm_set_ps1(m_style.get().mod_distort.pointsy[2]);
530 __dst213x = _mm_set_ps1(m_style.get().mod_distort.pointsx[1]); // 2 - 1 - 3
531 __dst213x = _mm_sub_ps(__dst213x, __dst1x);
532 __dst213x = _mm_sub_ps(__dst213x, __dst3x);
534 __dst213y = _mm_set_ps1(m_style.get().mod_distort.pointsy[1]);
535 __dst213x = _mm_sub_ps(__dst213y, __dst1y);
536 __dst213x = _mm_sub_ps(__dst213y, __dst3y);
538 #endif
540 __m128 __caz = _mm_set_ps1(caz);
541 __m128 __saz = _mm_set_ps1(saz);
542 __m128 __cax = _mm_set_ps1(cax);
543 __m128 __sax = _mm_set_ps1(sax);
544 __m128 __cay = _mm_set_ps1(cay);
545 __m128 __say = _mm_set_ps1(say);
547 // this can be paralleled for openmp
548 int mPathPointsD4 = path_data->mPathPoints / 4;
549 int mPathPointsM4 = path_data->mPathPoints % 4;
551 for(ptrdiff_t i = 0; i < mPathPointsD4 + 1; i++) {
552 POINT* const temp_points = path_data->mpPathPoints + 4 * i;
554 __m128 __pointx, __pointy;
555 // we can't use load .-.
556 if(i != mPathPointsD4) {
557 __pointx = _mm_set_ps(temp_points[0].x, temp_points[1].x, temp_points[2].x, temp_points[3].x);
558 __pointy = _mm_set_ps(temp_points[0].y, temp_points[1].y, temp_points[2].y, temp_points[3].y);
559 } else { // last cycle
560 switch(mPathPointsM4) {
561 default:
562 case 0:
563 continue;
564 case 1:
565 __pointx = _mm_set_ps(temp_points[0].x, 0, 0, 0);
566 __pointy = _mm_set_ps(temp_points[0].y, 0, 0, 0);
567 break;
568 case 2:
569 __pointx = _mm_set_ps(temp_points[0].x, temp_points[1].x, 0, 0);
570 __pointy = _mm_set_ps(temp_points[0].y, temp_points[1].y, 0, 0);
571 break;
572 case 3:
573 __pointx = _mm_set_ps(temp_points[0].x, temp_points[1].x, temp_points[2].x, 0);
574 __pointy = _mm_set_ps(temp_points[0].y, temp_points[1].y, temp_points[2].y, 0);
575 break;
579 #ifdef _VSMOD
580 __m128 __pointz = _mm_set_ps1(m_style.get().mod_z);
582 // distort
583 if(is_dist) {
584 //P = P0 + (P1 - P0)u + (P3 - P0)v + (P0 + P2 - P1 - P3)uv
585 __m128 __u = _mm_sub_ps(__pointx, __minx);
586 __m128 __v = _mm_sub_ps(__pointy, __miny);
587 __m128 __1_xsz = _mm_rcp_ps(__xsz);
588 __m128 __1_ysz = _mm_rcp_ps(__ysz);
589 __u = _mm_mul_ps(__u, __1_xsz);
590 __v = _mm_mul_ps(__v, __1_ysz);
592 // x
593 __pointx = _mm_mul_ps(__dst213x, __u);
594 __pointx = _mm_mul_ps(__pointx, __v);
596 __m128 __tmpx = _mm_mul_ps(__dst3x, __v);
597 __pointx = _mm_add_ps(__pointx, __tmpx);
598 __tmpx = _mm_mul_ps(__dst1x, __u);
599 __pointx = _mm_add_ps(__pointx, __tmpx);
601 __pointx = _mm_mul_ps(__pointx, __xsz);
602 __pointx = _mm_add_ps(__pointx, __minx);
604 // y
605 __pointy = _mm_mul_ps(__dst213y, __u);
606 __pointy = _mm_mul_ps(__pointy, __v);
608 __m128 __tmpy = _mm_mul_ps(__dst3y, __v);
609 __pointy = _mm_add_ps(__pointy, __tmpy);
610 __tmpy = _mm_mul_ps(__dst1y, __u);
611 __pointy = _mm_add_ps(__pointy, __tmpy);
613 __pointy = _mm_mul_ps(__pointy, __ysz);
614 __pointy = _mm_add_ps(__pointy, __miny);
617 // randomize
618 if(xrnd!=0 || yrnd!=0 || zrnd!=0) {
619 __declspec(align(16)) float rx[4], ry[4], rz[4];
620 for(int k=0; k<4; k++) {
621 rx[k] = xrnd > 0 ? (xrnd - rand() % (int)(xrnd * 2 + 1)) : 0;
622 ry[k] = yrnd > 0 ? (yrnd - rand() % (int)(yrnd * 2 + 1)) : 0;
623 rz[k] = zrnd > 0 ? (zrnd - rand() % (int)(zrnd * 2 + 1)) : 0;
625 __m128 __001 = _mm_set_ps1(0.01f);
627 if(xrnd!=0) {
628 __m128 __rx = _mm_load_ps(rx);
629 __rx = _mm_mul_ps(__rx, __001);
630 __pointx = _mm_add_ps(__pointx, __rx);
633 if(yrnd!=0) {
634 __m128 __ry = _mm_load_ps(ry);
635 __ry = _mm_mul_ps(__ry, __001);
636 __pointy = _mm_add_ps(__pointy, __ry);
639 if(zrnd!=0) {
640 __m128 __rz = _mm_load_ps(rz);
641 __rz = _mm_mul_ps(__rz, __001);
642 __pointz = _mm_add_ps(__pointz, __rz);
645 #else
646 __m128 __pointz = _mm_set_ps1(0);
647 #endif
649 // scale and shift
650 __m128 __tmpx;
651 if(m_style.get().fontShiftX!=0) {
652 __tmpx = _mm_mul_ps(__xshift, __pointy);
653 __tmpx = _mm_add_ps(__tmpx, __pointx);
654 } else {
655 __tmpx = __pointx;
657 __tmpx = _mm_mul_ps(__tmpx, __xscale);
658 __tmpx = _mm_sub_ps(__tmpx, __xorg);
660 __m128 __tmpy;
661 if(m_style.get().fontShiftY!=0) {
662 __tmpy = _mm_mul_ps(__yshift, __pointx);
663 __tmpy = _mm_add_ps(__tmpy, __pointy);
664 } else {
665 __tmpy = __pointy;
667 __tmpy = _mm_mul_ps(__tmpy, __yscale);
668 __tmpy = _mm_sub_ps(__tmpy, __yorg);
670 // rotate
671 __m128 __xx = _mm_mul_ps(__tmpx, __caz);
672 __m128 __yy = _mm_mul_ps(__tmpy, __saz);
673 __pointx = _mm_add_ps(__xx, __yy);
674 __xx = _mm_mul_ps(__tmpx, __saz);
675 __yy = _mm_mul_ps(__tmpy, __caz);
676 __pointy = _mm_sub_ps(__yy, __xx);
678 __m128 __zz = _mm_mul_ps(__pointz, __sax);
679 __yy = _mm_mul_ps(__pointy, __cax);
680 __pointy = _mm_add_ps(__yy, __zz);
681 __zz = _mm_mul_ps(__pointz, __cax);
682 __yy = _mm_mul_ps(__pointy, __sax);
683 __pointz = _mm_sub_ps(__zz, __yy);
685 __xx = _mm_mul_ps(__pointx, __cay);
686 __zz = _mm_mul_ps(__pointz, __say);
687 __pointx = _mm_add_ps(__xx, __zz);
688 __xx = _mm_mul_ps(__pointx, __say);
689 __zz = _mm_mul_ps(__pointz, __cay);
690 __pointz = _mm_sub_ps(__xx, __zz);
692 __zz = _mm_set_ps1(-19000);
693 __pointz = _mm_max_ps(__pointz, __zz);
695 __m128 __20000 = _mm_set_ps1(20000);
696 __zz = _mm_add_ps(__pointz, __20000);
697 __zz = _mm_rcp_ps(__zz);
699 __pointx = _mm_mul_ps(__pointx, __20000);
700 __pointx = _mm_mul_ps(__pointx, __zz);
702 __pointy = _mm_mul_ps(__pointy, __20000);
703 __pointy = _mm_mul_ps(__pointy, __zz);
705 __pointx = _mm_add_ps(__pointx, __xorg);
706 __pointy = _mm_add_ps(__pointy, __yorg);
708 __m128 __05 = _mm_set_ps1(0.5);
710 __pointx = _mm_add_ps(__pointx, __05);
711 __pointy = _mm_add_ps(__pointy, __05);
713 if(i == mPathPointsD4) { // last cycle
714 for(int k=0; k<mPathPointsM4; k++) {
715 temp_points[k].x = static_cast<LONG>(__pointx.m128_f32[3-k]);
716 temp_points[k].y = static_cast<LONG>(__pointy.m128_f32[3-k]);
718 } else {
719 for(int k=0; k<4; k++) {
720 temp_points[k].x = static_cast<LONG>(__pointx.m128_f32[3-k]);
721 temp_points[k].y = static_cast<LONG>(__pointy.m128_f32[3-k]);
725 #endif // __ICL
728 bool CWord::CreateOpaqueBox()
730 if(m_pOpaqueBox) return(true);
731 STSStyle style = m_style.get();
732 style.borderStyle = 0;
733 style.outlineWidthX = style.outlineWidthY = 0;
734 style.colors[0] = m_style.get().colors[2];
735 style.alpha[0] = m_style.get().alpha[2];
736 int w = (int)(m_style.get().outlineWidthX + 0.5);
737 int h = (int)(m_style.get().outlineWidthY + 0.5);
738 CStringW str;
739 str.Format(L"m %d %d l %d %d %d %d %d %d",
740 -w, -h,
741 m_width+w, -h,
742 m_width+w, m_ascent+m_descent+h,
743 -w, m_ascent+m_descent+h);
744 m_pOpaqueBox.reset( new CPolygon(FwSTSStyle(style), str, 0, 0, 0, 1.0/8, 1.0/8, 0) );
745 return(!!m_pOpaqueBox);
748 // CText
750 CText::CText(const FwSTSStyle& style, const CStringW& str, int ktype, int kstart, int kend)
751 : CWord(style, str, ktype, kstart, kend)
753 if(m_str == L" ")
755 m_fWhiteSpaceChar = true;
757 FwCMyFont font(m_style);
758 HFONT hOldFont = SelectFont(g_hDC, font.get());
759 if(m_style.get().fontSpacing || (long)GetVersion() < 0)
761 bool bFirstPath = true;
762 for(LPCWSTR s = m_str; *s; s++)
764 CSize extent;
765 if(!GetTextExtentPoint32W(g_hDC, s, 1, &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return;}
766 m_width += extent.cx + (int)m_style.get().fontSpacing;
768 // m_width -= (int)m_style.get().fontSpacing; // TODO: subtract only at the end of the line
770 else
772 CSize extent;
773 if(!GetTextExtentPoint32W(g_hDC, m_str, wcslen(m_str), &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return;}
774 m_width += extent.cx;
776 m_width = (int)(m_style.get().fontScaleX/100*m_width + 4) >> 3;
777 SelectFont(g_hDC, hOldFont);
780 CText::CText( const CText& src ):CWord(src)
782 m_width = src.m_width;
785 SharedPtrCWord CText::Copy()
787 SharedPtrCWord result(new CText(*this));
788 return result;
791 bool CText::Append(const SharedPtrCWord& w)
793 return (w && CWord::Append(w));
796 bool CText::CreatePath(const SharedPtrPathData& path_data)
798 FwCMyFont font(m_style);
799 HFONT hOldFont = SelectFont(g_hDC, font.get());
800 int width = 0;
801 if(m_style.get().fontSpacing || (long)GetVersion() < 0)
803 bool bFirstPath = true;
804 for(LPCWSTR s = m_str; *s; s++)
806 CSize extent;
807 if(!GetTextExtentPoint32W(g_hDC, s, 1, &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return(false);}
808 path_data->PartialBeginPath(g_hDC, bFirstPath);
809 bFirstPath = false;
810 TextOutW(g_hDC, 0, 0, s, 1);
811 path_data->PartialEndPath(g_hDC, width, 0);
812 width += extent.cx + (int)m_style.get().fontSpacing;
815 else
817 CSize extent;
818 if(!GetTextExtentPoint32W(g_hDC, m_str, m_str.GetLength(), &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return(false);}
819 path_data->BeginPath(g_hDC);
820 TextOutW(g_hDC, 0, 0, m_str, m_str.GetLength());
821 path_data->EndPath(g_hDC);
823 SelectFont(g_hDC, hOldFont);
824 return(true);
827 // CPolygon
829 CPolygon::CPolygon(const FwSTSStyle& style, const CStringW& str, int ktype, int kstart, int kend, double scalex, double scaley, int baseline)
830 : CWord(style, str, ktype, kstart, kend)
831 , m_scalex(scalex), m_scaley(scaley), m_baseline(baseline)
833 ParseStr();
836 CPolygon::CPolygon(CPolygon& src) : CWord(src)
838 m_scalex = src.m_scalex;
839 m_scaley = src.m_scaley;
840 m_baseline = src.m_baseline;
841 m_width = src.m_width;
842 m_ascent = src.m_ascent;
843 m_descent = src.m_descent;
844 m_pathTypesOrg.Copy(src.m_pathTypesOrg);
845 m_pathPointsOrg.Copy(src.m_pathPointsOrg);
847 CPolygon::~CPolygon()
851 SharedPtrCWord CPolygon::Copy()
853 SharedPtrCWord result(DNew CPolygon(*this));
854 return result;
857 bool CPolygon::Append(const SharedPtrCWord& w)
859 // TODO
860 return(false);
863 bool CPolygon::GetLONG(CStringW& str, LONG& ret)
865 LPWSTR s = (LPWSTR)(LPCWSTR)str, e = s;
866 ret = wcstol(str, &e, 10);
867 str = str.Mid(e - s);
868 return(e > s);
871 bool CPolygon::GetPOINT(CStringW& str, POINT& ret)
873 return(GetLONG(str, ret.x) && GetLONG(str, ret.y));
876 bool CPolygon::ParseStr()
878 if(m_pathTypesOrg.GetCount() > 0) return(true);
879 CPoint p;
880 int j, lastsplinestart = -1, firstmoveto = -1, lastmoveto = -1;
881 CStringW str = m_str;
882 str.SpanIncluding(L"mnlbspc 0123456789");
883 str.Replace(L"m", L"*m");
884 str.Replace(L"n", L"*n");
885 str.Replace(L"l", L"*l");
886 str.Replace(L"b", L"*b");
887 str.Replace(L"s", L"*s");
888 str.Replace(L"p", L"*p");
889 str.Replace(L"c", L"*c");
890 int k = 0;
891 for(CStringW s = str.Tokenize(L"*", k); !s.IsEmpty(); s = str.Tokenize(L"*", k))
893 WCHAR c = s[0];
894 s.TrimLeft(L"mnlbspc ");
895 switch(c)
897 case 'm':
898 lastmoveto = m_pathTypesOrg.GetCount();
899 if(firstmoveto == -1) firstmoveto = lastmoveto;
900 while(GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_MOVETO); m_pathPointsOrg.Add(p);}
901 break;
902 case 'n':
903 while(GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_MOVETONC); m_pathPointsOrg.Add(p);}
904 break;
905 case 'l':
906 while(GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_LINETO); m_pathPointsOrg.Add(p);}
907 break;
908 case 'b':
909 j = m_pathTypesOrg.GetCount();
910 while(GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_BEZIERTO); m_pathPointsOrg.Add(p); j++;}
911 j = m_pathTypesOrg.GetCount() - ((m_pathTypesOrg.GetCount()-j)%3);
912 m_pathTypesOrg.SetCount(j);
913 m_pathPointsOrg.SetCount(j);
914 break;
915 case 's':
917 j = lastsplinestart = m_pathTypesOrg.GetCount();
918 int i = 3;
919 while(i-- && GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_BSPLINETO); m_pathPointsOrg.Add(p); j++;}
920 if(m_pathTypesOrg.GetCount()-lastsplinestart < 3) {m_pathTypesOrg.SetCount(lastsplinestart); m_pathPointsOrg.SetCount(lastsplinestart); lastsplinestart = -1;}
922 // no break here
923 case 'p':
924 while(GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_BSPLINEPATCHTO); m_pathPointsOrg.Add(p); j++;}
925 break;
926 case 'c':
927 if(lastsplinestart > 0)
929 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
930 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
931 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
932 p = m_pathPointsOrg[lastsplinestart-1]; // we need p for temp storage, because operator [] will return a reference to CPoint and Add() may reallocate its internal buffer (this is true for MFC 7.0 but not for 6.0, hehe)
933 m_pathPointsOrg.Add(p);
934 p = m_pathPointsOrg[lastsplinestart];
935 m_pathPointsOrg.Add(p);
936 p = m_pathPointsOrg[lastsplinestart+1];
937 m_pathPointsOrg.Add(p);
938 lastsplinestart = -1;
940 break;
941 default:
942 break;
946 LPCWSTR str = m_str;
947 while(*str)
949 while(*str && *str != 'm' && *str != 'n' && *str != 'l' && *str != 'b' && *str != 's' && *str != 'p' && *str != 'c') str++;
951 if(!*str) break;
953 switch(*str++)
955 case 'm':
956 lastmoveto = m_pathTypesOrg.GetCount();
957 if(firstmoveto == -1) firstmoveto = lastmoveto;
958 while(GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_MOVETO); m_pathPointsOrg.Add(p);}
959 break;
960 case 'n':
961 while(GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_MOVETONC); m_pathPointsOrg.Add(p);}
962 break;
963 case 'l':
964 while(GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_LINETO); m_pathPointsOrg.Add(p);}
965 break;
966 case 'b':
967 j = m_pathTypesOrg.GetCount();
968 while(GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_BEZIERTO); m_pathPointsOrg.Add(p); j++;}
969 j = m_pathTypesOrg.GetCount() - ((m_pathTypesOrg.GetCount()-j)%3);
970 m_pathTypesOrg.SetCount(j); m_pathPointsOrg.SetCount(j);
971 break;
972 case 's':
973 j = lastsplinestart = m_pathTypesOrg.GetCount();
974 i = 3;
975 while(i-- && GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_BSPLINETO); m_pathPointsOrg.Add(p); j++;}
976 if(m_pathTypesOrg.GetCount()-lastsplinestart < 3) {m_pathTypesOrg.SetCount(lastsplinestart); m_pathPointsOrg.SetCount(lastsplinestart); lastsplinestart = -1;}
977 // no break here
978 case 'p':
979 while(GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_BSPLINEPATCHTO); m_pathPointsOrg.Add(p); j++;}
980 break;
981 case 'c':
982 if(lastsplinestart > 0)
984 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
985 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
986 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
987 p = m_pathPointsOrg[lastsplinestart-1]; // we need p for temp storage, because operator [] will return a reference to CPoint and Add() may reallocate its internal buffer (this is true for MFC 7.0 but not for 6.0, hehe)
988 m_pathPointsOrg.Add(p);
989 p = m_pathPointsOrg[lastsplinestart];
990 m_pathPointsOrg.Add(p);
991 p = m_pathPointsOrg[lastsplinestart+1];
992 m_pathPointsOrg.Add(p);
993 lastsplinestart = -1;
995 break;
996 default:
997 break;
1000 if(firstmoveto > 0) break;
1003 if(lastmoveto == -1 || firstmoveto > 0)
1005 m_pathTypesOrg.RemoveAll();
1006 m_pathPointsOrg.RemoveAll();
1007 return(false);
1009 int minx = INT_MAX, miny = INT_MAX, maxx = -INT_MAX, maxy = -INT_MAX;
1010 for(size_t i = 0; i < m_pathTypesOrg.GetCount(); i++)
1012 m_pathPointsOrg[i].x = (int)(64 * m_scalex * m_pathPointsOrg[i].x);
1013 m_pathPointsOrg[i].y = (int)(64 * m_scaley * m_pathPointsOrg[i].y);
1014 if(minx > m_pathPointsOrg[i].x) minx = m_pathPointsOrg[i].x;
1015 if(miny > m_pathPointsOrg[i].y) miny = m_pathPointsOrg[i].y;
1016 if(maxx < m_pathPointsOrg[i].x) maxx = m_pathPointsOrg[i].x;
1017 if(maxy < m_pathPointsOrg[i].y) maxy = m_pathPointsOrg[i].y;
1019 m_width = max(maxx - minx, 0);
1020 m_ascent = max(maxy - miny, 0);
1021 int baseline = (int)(64 * m_scaley * m_baseline);
1022 m_descent = baseline;
1023 m_ascent -= baseline;
1024 m_width = ((int)(m_style.get().fontScaleX/100 * m_width) + 4) >> 3;
1025 m_ascent = ((int)(m_style.get().fontScaleY/100 * m_ascent) + 4) >> 3;
1026 m_descent = ((int)(m_style.get().fontScaleY/100 * m_descent) + 4) >> 3;
1027 return(true);
1030 bool CPolygon::CreatePath(const SharedPtrPathData& path_data)
1032 int len = m_pathTypesOrg.GetCount();
1033 if(len == 0) return(false);
1034 if(path_data->mPathPoints != len)
1036 path_data->mpPathTypes = (BYTE*)realloc(path_data->mpPathTypes, len*sizeof(BYTE));
1037 path_data->mpPathPoints = (POINT*)realloc(path_data->mpPathPoints, len*sizeof(POINT));
1038 if(!path_data->mpPathTypes || !path_data->mpPathPoints) return(false);
1039 path_data->mPathPoints = len;
1041 memcpy(path_data->mpPathTypes, m_pathTypesOrg.GetData(), len*sizeof(BYTE));
1042 memcpy(path_data->mpPathPoints, m_pathPointsOrg.GetData(), len*sizeof(POINT));
1043 return(true);
1046 // CClipper
1048 CClipper::CClipper(CStringW str, CSize size, double scalex, double scaley, bool inverse)
1049 : m_polygon( new CPolygon(FwSTSStyle(), str, 0, 0, 0, scalex, scaley, 0) )
1051 m_size.cx = m_size.cy = 0;
1052 //m_pAlphaMask = NULL;
1053 if(size.cx < 0 || size.cy < 0)
1054 return;
1055 m_pAlphaMask.reset(new BYTE[size.cx*size.cy]);
1056 if( !m_pAlphaMask )
1057 return;
1058 m_size = size;
1059 m_inverse = inverse;
1060 memset( m_pAlphaMask.get(), 0, size.cx*size.cy);
1061 OverlayList overlay_list;
1062 CWord::Paint( m_polygon, CPoint(0, 0), CPoint(0, 0), &overlay_list );
1063 int w = overlay_list.overlay->mOverlayWidth, h = overlay_list.overlay->mOverlayHeight;
1064 int x = (overlay_list.overlay->mOffsetX+4)>>3, y = (overlay_list.overlay->mOffsetY+4)>>3;
1065 int xo = 0, yo = 0;
1066 if(x < 0) {xo = -x; w -= -x; x = 0;}
1067 if(y < 0) {yo = -y; h -= -y; y = 0;}
1068 if(x+w > m_size.cx) w = m_size.cx-x;
1069 if(y+h > m_size.cy) h = m_size.cy-y;
1070 if(w <= 0 || h <= 0) return;
1071 const BYTE* src = overlay_list.overlay->mpOverlayBuffer.body + (overlay_list.overlay->mOverlayPitch * yo + xo);
1072 BYTE* dst = m_pAlphaMask.get() + m_size.cx * y + x;
1073 while(h--)
1075 //for(int wt=0; wt<w; ++wt)
1076 // dst[wt] = src[wt];
1077 memcpy(dst, src, w);
1078 src += overlay_list.overlay->mOverlayPitch;
1079 dst += m_size.cx;
1081 if(inverse)
1083 BYTE* dst = m_pAlphaMask.get();
1084 for(int i = size.cx*size.cy; i>0; --i, ++dst)
1085 *dst = 0x40 - *dst; // mask is 6 bit
1089 CClipper::~CClipper()
1091 m_pAlphaMask.reset(NULL);
1094 // CLine
1096 CLine::~CLine()
1098 //POSITION pos = GetHeadPosition();
1099 //while(pos) delete GetNext(pos);
1102 void CLine::Compact()
1104 POSITION pos = GetHeadPosition();
1105 while(pos)
1107 SharedPtrCWord w = GetNext(pos);
1108 if(!w->m_fWhiteSpaceChar) break;
1109 m_width -= w->m_width;
1110 // delete w;
1111 RemoveHead();
1113 pos = GetTailPosition();
1114 while(pos)
1116 SharedPtrCWord w = GetPrev(pos);
1117 if(!w->m_fWhiteSpaceChar) break;
1118 m_width -= w->m_width;
1119 // delete w;
1120 RemoveTail();
1122 if(IsEmpty()) return;
1123 CLine l;
1124 l.AddTailList(this);
1125 RemoveAll();
1126 SharedPtrCWord last;
1127 pos = l.GetHeadPosition();
1128 while(pos)
1130 SharedPtrCWord w = l.GetNext(pos);
1131 if(!last || !last->Append(w))
1132 AddTail(last = w->Copy());
1134 m_ascent = m_descent = m_borderX = m_borderY = 0;
1135 pos = GetHeadPosition();
1136 while(pos)
1138 SharedPtrCWord w = GetNext(pos);
1139 if(m_ascent < w->m_ascent) m_ascent = w->m_ascent;
1140 if(m_descent < w->m_descent) m_descent = w->m_descent;
1141 if(m_borderX < w->m_style.get().outlineWidthX) m_borderX = (int)(w->m_style.get().outlineWidthX+0.5);
1142 if(m_borderY < w->m_style.get().outlineWidthY) m_borderY = (int)(w->m_style.get().outlineWidthY+0.5);
1146 CRect CLine::PaintShadow(CompositeDrawItemList* output, SubPicDesc& spd, CRect& clipRect, SharedArrayByte pAlphaMask, CPoint p, CPoint org, int time, int alpha)
1148 CRect bbox(0, 0, 0, 0);
1149 POSITION pos = GetHeadPosition();
1150 POSITION outputPos = output->GetHeadPosition();
1151 while(pos)
1153 SharedPtrCWord w = GetNext(pos);
1154 CompositeDrawItem& outputItem = output->GetNext(outputPos);
1156 if(w->m_fLineBreak) return(bbox); // should not happen since this class is just a line of text without any breaks
1157 if(w->m_style.get().shadowDepthX != 0 || w->m_style.get().shadowDepthY != 0)
1159 int x = p.x + (int)(w->m_style.get().shadowDepthX+0.5);
1160 int y = p.y + m_ascent - w->m_ascent + (int)(w->m_style.get().shadowDepthY+0.5);
1161 DWORD a = 0xff - w->m_style.get().alpha[3];
1162 if(alpha > 0) a = MulDiv(a, 0xff - alpha, 0xff);
1163 COLORREF shadow = revcolor(w->m_style.get().colors[3]) | (a<<24);
1164 DWORD sw[6] = {shadow, -1};
1165 //xy
1166 if(spd.type == MSP_AUYV)
1168 sw[0] =rgb2yuv(sw[0], XY_AUYV);
1170 else if(spd.type == MSP_AYUV || spd.type == MSP_AY11)
1172 sw[0] =rgb2yuv(sw[0], XY_AYUV);
1174 OverlayList overlay_list;
1175 CWord::Paint(w, CPoint(x, y), org, &overlay_list);
1176 if(w->m_style.get().borderStyle == 0)
1178 outputItem.shadow.reset(
1179 Rasterizer::CreateDrawItem(spd, overlay_list.overlay, clipRect, pAlphaMask, x, y, sw,
1180 w->m_ktype > 0 || w->m_style.get().alpha[0] < 0xff,
1181 (w->m_style.get().outlineWidthX+w->m_style.get().outlineWidthY > 0) && !(w->m_ktype == 2 && time < w->m_kstart))
1183 bbox |= Rasterizer::DryDraw(spd, *outputItem.shadow);
1185 else if(w->m_style.get().borderStyle == 1 && w->m_pOpaqueBox)
1187 outputItem.shadow.reset(
1188 Rasterizer::CreateDrawItem(spd, overlay_list.next->overlay, clipRect, pAlphaMask, x, y, sw, true, false)
1190 bbox |= Rasterizer::DryDraw(spd, *outputItem.shadow);
1193 p.x += w->m_width;
1195 return(bbox);
1198 CRect CLine::PaintOutline(CompositeDrawItemList* output, SubPicDesc& spd, CRect& clipRect, SharedArrayByte pAlphaMask, CPoint p, CPoint org, int time, int alpha)
1200 CRect bbox(0, 0, 0, 0);
1201 POSITION pos = GetHeadPosition();
1202 POSITION outputPos = output->GetHeadPosition();
1203 while(pos)
1205 SharedPtrCWord w = GetNext(pos);
1206 CompositeDrawItem& outputItem = output->GetNext(outputPos);
1207 if(w->m_fLineBreak) return(bbox); // should not happen since this class is just a line of text without any breaks
1208 if(w->m_style.get().outlineWidthX+w->m_style.get().outlineWidthY > 0 && !(w->m_ktype == 2 && time < w->m_kstart))
1210 int x = p.x;
1211 int y = p.y + m_ascent - w->m_ascent;
1212 DWORD aoutline = w->m_style.get().alpha[2];
1213 if(alpha > 0) aoutline += MulDiv(alpha, 0xff - w->m_style.get().alpha[2], 0xff);
1214 COLORREF outline = revcolor(w->m_style.get().colors[2]) | ((0xff-aoutline)<<24);
1215 DWORD sw[6] = {outline, -1};
1216 //xy
1217 if(spd.type == MSP_AUYV)
1219 sw[0] =rgb2yuv(sw[0], XY_AUYV);
1221 else if(spd.type == MSP_AYUV || spd.type == MSP_AY11)
1223 sw[0] =rgb2yuv(sw[0], XY_AYUV);
1225 OverlayList overlay_list;
1226 CWord::Paint(w, CPoint(x, y), org, &overlay_list);
1227 if(w->m_style.get().borderStyle == 0)
1229 outputItem.outline.reset(
1230 Rasterizer::CreateDrawItem(spd, overlay_list.overlay, clipRect, pAlphaMask, x, y, sw, !w->m_style.get().alpha[0] && !w->m_style.get().alpha[1] && !alpha, true)
1232 bbox |= Rasterizer::DryDraw(spd, *outputItem.outline);
1234 else if(w->m_style.get().borderStyle == 1 && w->m_pOpaqueBox)
1236 outputItem.outline.reset(
1237 Rasterizer::CreateDrawItem(spd, overlay_list.next->overlay, clipRect, pAlphaMask, x, y, sw, true, false)
1239 bbox |= Rasterizer::DryDraw(spd, *outputItem.outline);
1242 p.x += w->m_width;
1244 return(bbox);
1247 CRect CLine::PaintBody(CompositeDrawItemList* output, SubPicDesc& spd, CRect& clipRect, SharedArrayByte pAlphaMask, CPoint p, CPoint org, int time, int alpha)
1249 CRect bbox(0, 0, 0, 0);
1250 POSITION pos = GetHeadPosition();
1251 POSITION outputPos = output->GetHeadPosition();
1252 while(pos)
1254 SharedPtrCWord w = GetNext(pos);
1255 CompositeDrawItem& outputItem = output->GetNext(outputPos);
1256 if(w->m_fLineBreak) return(bbox); // should not happen since this class is just a line of text without any breaks
1257 int x = p.x;
1258 int y = p.y + m_ascent - w->m_ascent;
1259 // colors
1260 DWORD aprimary = w->m_style.get().alpha[0];
1261 if(alpha > 0) aprimary += MulDiv(alpha, 0xff - w->m_style.get().alpha[0], 0xff);
1262 COLORREF primary = revcolor(w->m_style.get().colors[0]) | ((0xff-aprimary)<<24);
1263 DWORD asecondary = w->m_style.get().alpha[1];
1264 if(alpha > 0) asecondary += MulDiv(alpha, 0xff - w->m_style.get().alpha[1], 0xff);
1265 COLORREF secondary = revcolor(w->m_style.get().colors[1]) | ((0xff-asecondary)<<24);
1266 DWORD sw[6] = {primary, 0, secondary};
1267 // karaoke
1268 double t;
1269 if(w->m_ktype == 0 || w->m_ktype == 2)
1271 t = time < w->m_kstart ? 0 : 1;
1273 else if(w->m_ktype == 1)
1275 if(time < w->m_kstart) t = 0;
1276 else if(time < w->m_kend)
1278 t = 1.0 * (time - w->m_kstart) / (w->m_kend - w->m_kstart);
1279 double angle = fmod(w->m_style.get().fontAngleZ, 360.0);
1280 if(angle > 90 && angle < 270)
1282 t = 1-t;
1283 COLORREF tmp = sw[0];
1284 sw[0] = sw[2];
1285 sw[2] = tmp;
1288 else t = 1.0;
1290 if(t >= 1)
1292 sw[1] = 0xffffffff;
1294 sw[3] = (int)(w->m_style.get().outlineWidthX + t*w->m_width) >> 3;
1295 sw[4] = sw[2];
1296 sw[5] = 0x00ffffff;
1297 //xy
1298 if(spd.type == MSP_AUYV)
1300 sw[0] =rgb2yuv(sw[0], XY_AUYV);
1301 sw[2] =rgb2yuv(sw[2], XY_AUYV);
1302 sw[4] =rgb2yuv(sw[4], XY_AUYV);
1304 else if(spd.type == MSP_AYUV || spd.type == MSP_AY11)
1306 sw[0] =rgb2yuv(sw[0], XY_AYUV);
1307 sw[2] =rgb2yuv(sw[2], XY_AYUV);
1308 sw[4] =rgb2yuv(sw[4], XY_AYUV);
1310 OverlayList overlay_list;
1311 CWord::Paint(w, CPoint(x, y), org, &overlay_list);
1312 outputItem.body.reset(
1313 Rasterizer::CreateDrawItem(spd, overlay_list.overlay, clipRect, pAlphaMask, x, y, sw, true, false)
1315 bbox |= Rasterizer::DryDraw(spd, *outputItem.body);
1316 p.x += w->m_width;
1318 return(bbox);
1321 void CLine::AddWord2Tail( SharedPtrCWord words )
1323 __super::AddTail(words);
1326 bool CLine::IsEmpty()
1328 return __super::IsEmpty();
1331 int CLine::GetWordCount()
1333 return GetCount();
1337 // CSubtitle
1339 CSubtitle::CSubtitle()
1341 memset(m_effects, 0, sizeof(Effect*)*EF_NUMBEROFEFFECTS);
1342 m_pClipper = NULL;
1343 m_clipInverse = false;
1344 m_scalex = m_scaley = 1;
1345 m_fAnimated2 = false;
1348 CSubtitle::~CSubtitle()
1350 Empty();
1353 void CSubtitle::Empty()
1355 POSITION pos = GetHeadPosition();
1356 while(pos) delete GetNext(pos);
1357 // pos = m_words.GetHeadPosition();
1358 // while(pos) delete m_words.GetNext(pos);
1359 for(int i = 0; i < EF_NUMBEROFEFFECTS; i++) {if(m_effects[i]) delete m_effects[i];}
1360 memset(m_effects, 0, sizeof(Effect*)*EF_NUMBEROFEFFECTS);
1361 if(m_pClipper) delete m_pClipper;
1362 m_pClipper = NULL;
1365 int CSubtitle::GetFullWidth()
1367 int width = 0;
1368 POSITION pos = m_words.GetHeadPosition();
1369 while(pos) width += m_words.GetNext(pos)->m_width;
1370 return(width);
1373 int CSubtitle::GetFullLineWidth(POSITION pos)
1375 int width = 0;
1376 while(pos)
1378 SharedPtrCWord w = m_words.GetNext(pos);
1379 if(w->m_fLineBreak) break;
1380 width += w->m_width;
1382 return(width);
1385 int CSubtitle::GetWrapWidth(POSITION pos, int maxwidth)
1387 if(m_wrapStyle == 0 || m_wrapStyle == 3)
1389 if(maxwidth > 0)
1391 // int fullwidth = GetFullWidth();
1392 int fullwidth = GetFullLineWidth(pos);
1393 int minwidth = fullwidth / ((abs(fullwidth) / maxwidth) + 1);
1394 int width = 0, wordwidth = 0;
1395 while(pos && width < minwidth)
1397 SharedPtrCWord w = m_words.GetNext(pos);
1398 wordwidth = w->m_width;
1399 if(abs(width + wordwidth) < abs(maxwidth)) width += wordwidth;
1401 maxwidth = width;
1402 if(m_wrapStyle == 3 && pos) maxwidth -= wordwidth;
1405 else if(m_wrapStyle == 1)
1407 // maxwidth = maxwidth;
1409 else if(m_wrapStyle == 2)
1411 maxwidth = INT_MAX;
1413 return(maxwidth);
1416 CLine* CSubtitle::GetNextLine(POSITION& pos, int maxwidth)
1418 if(pos == NULL) return(NULL);
1419 CLine* ret = new CLine();
1420 if(!ret) return(NULL);
1421 ret->m_width = ret->m_ascent = ret->m_descent = ret->m_borderX = ret->m_borderY = 0;
1422 maxwidth = GetWrapWidth(pos, maxwidth);
1423 bool fEmptyLine = true;
1424 while(pos)
1426 SharedPtrCWord w = m_words.GetNext(pos);
1427 if(ret->m_ascent < w->m_ascent) ret->m_ascent = w->m_ascent;
1428 if(ret->m_descent < w->m_descent) ret->m_descent = w->m_descent;
1429 if(ret->m_borderX < w->m_style.get().outlineWidthX) ret->m_borderX = (int)(w->m_style.get().outlineWidthX+0.5);
1430 if(ret->m_borderY < w->m_style.get().outlineWidthY) ret->m_borderY = (int)(w->m_style.get().outlineWidthY+0.5);
1431 if(w->m_fLineBreak)
1433 if(fEmptyLine) {ret->m_ascent /= 2; ret->m_descent /= 2; ret->m_borderX = ret->m_borderY = 0;}
1434 ret->Compact();
1435 return(ret);
1437 fEmptyLine = false;
1438 bool fWSC = w->m_fWhiteSpaceChar;
1439 int width = w->m_width;
1440 POSITION pos2 = pos;
1441 while(pos2)
1443 if(m_words.GetAt(pos2)->m_fWhiteSpaceChar != fWSC
1444 || m_words.GetAt(pos2)->m_fLineBreak) break;
1445 SharedPtrCWord w2 = m_words.GetNext(pos2);
1446 width += w2->m_width;
1448 if((ret->m_width += width) <= maxwidth || ret->IsEmpty())
1450 ret->AddWord2Tail(w);
1451 while(pos != pos2)
1453 ret->AddWord2Tail(m_words.GetNext(pos));
1455 pos = pos2;
1457 else
1459 if(pos) m_words.GetPrev(pos);
1460 else pos = m_words.GetTailPosition();
1461 ret->m_width -= width;
1462 break;
1465 ret->Compact();
1466 return(ret);
1469 void CSubtitle::CreateClippers(CSize size)
1471 size.cx >>= 3;
1472 size.cy >>= 3;
1473 if(m_effects[EF_BANNER] && m_effects[EF_BANNER]->param[2])
1475 int width = m_effects[EF_BANNER]->param[2];
1476 int w = size.cx, h = size.cy;
1477 if(!m_pClipper)
1479 CStringW str;
1480 str.Format(L"m %d %d l %d %d %d %d %d %d", 0, 0, w, 0, w, h, 0, h);
1481 m_pClipper = new CClipper(str, size, 1, 1, false);
1482 if(!m_pClipper) return;
1484 int da = (64<<8)/width;
1485 BYTE* am = m_pClipper->m_pAlphaMask.get();
1486 for(int j = 0; j < h; j++, am += w)
1488 int a = 0;
1489 int k = min(width, w);
1490 for(int i = 0; i < k; i++, a += da)
1491 am[i] = (am[i]*a)>>14;
1492 a = 0x40<<8;
1493 k = w-width;
1494 if(k < 0) {a -= -k*da; k = 0;}
1495 for(int i = k; i < w; i++, a -= da)
1496 am[i] = (am[i]*a)>>14;
1499 else if(m_effects[EF_SCROLL] && m_effects[EF_SCROLL]->param[4])
1501 int height = m_effects[EF_SCROLL]->param[4];
1502 int w = size.cx, h = size.cy;
1503 if(!m_pClipper)
1505 CStringW str;
1506 str.Format(L"m %d %d l %d %d %d %d %d %d", 0, 0, w, 0, w, h, 0, h);
1507 m_pClipper = new CClipper(str, size, 1, 1, false);
1508 if(!m_pClipper) return;
1510 int da = (64<<8)/height;
1511 int a = 0;
1512 int k = m_effects[EF_SCROLL]->param[0]>>3;
1513 int l = k+height;
1514 if(k < 0) {a += -k*da; k = 0;}
1515 if(l > h) {l = h;}
1516 if(k < h)
1518 BYTE* am = &m_pClipper->m_pAlphaMask[k*w];
1519 memset(m_pClipper->m_pAlphaMask.get(), 0, am - m_pClipper->m_pAlphaMask.get());
1520 for(int j = k; j < l; j++, a += da)
1522 for(int i = 0; i < w; i++, am++)
1523 *am = ((*am)*a)>>14;
1526 da = -(64<<8)/height;
1527 a = 0x40<<8;
1528 l = m_effects[EF_SCROLL]->param[1]>>3;
1529 k = l-height;
1530 if(k < 0) {a += -k*da; k = 0;}
1531 if(l > h) {l = h;}
1532 if(k < h)
1534 BYTE* am = &m_pClipper->m_pAlphaMask[k*w];
1535 int j = k;
1536 for(; j < l; j++, a += da)
1538 for(int i = 0; i < w; i++, am++)
1539 *am = ((*am)*a)>>14;
1541 memset(am, 0, (h-j)*w);
1546 void CSubtitle::MakeLines(CSize size, CRect marginRect)
1548 CSize spaceNeeded(0, 0);
1549 bool fFirstLine = true;
1550 m_topborder = m_bottomborder = 0;
1551 CLine* l = NULL;
1552 POSITION pos = m_words.GetHeadPosition();
1553 while(pos)
1555 l = GetNextLine(pos, size.cx - marginRect.left - marginRect.right);
1556 if(!l) break;
1557 if(fFirstLine) {m_topborder = l->m_borderY; fFirstLine = false;}
1558 spaceNeeded.cx = max(l->m_width+l->m_borderX, spaceNeeded.cx);
1559 spaceNeeded.cy += l->m_ascent + l->m_descent;
1560 AddTail(l);
1562 if(l) m_bottomborder = l->m_borderY;
1563 m_rect = CRect(
1564 CPoint((m_scrAlignment%3) == 1 ? marginRect.left
1565 : (m_scrAlignment%3) == 2 ? (marginRect.left + (size.cx - marginRect.right) - spaceNeeded.cx + 1) / 2
1566 : (size.cx - marginRect.right - spaceNeeded.cx),
1567 m_scrAlignment <= 3 ? (size.cy - marginRect.bottom - spaceNeeded.cy)
1568 : m_scrAlignment <= 6 ? (marginRect.top + (size.cy - marginRect.bottom) - spaceNeeded.cy + 1) / 2
1569 : marginRect.top),
1570 spaceNeeded);
1573 POSITION CSubtitle::GetHeadLinePosition()
1575 return __super::GetHeadPosition();
1578 CLine* CSubtitle::GetNextLine( POSITION& pos )
1580 return __super::GetNext(pos);
1583 // CScreenLayoutAllocator
1585 void CScreenLayoutAllocator::Empty()
1587 m_subrects.RemoveAll();
1590 void CScreenLayoutAllocator::AdvanceToSegment(int segment, const CAtlArray<int>& sa)
1592 POSITION pos = m_subrects.GetHeadPosition();
1593 while(pos)
1595 POSITION prev = pos;
1596 SubRect& sr = m_subrects.GetNext(pos);
1597 bool fFound = false;
1598 if(abs(sr.segment - segment) <= 1) // using abs() makes it possible to play the subs backwards, too :)
1600 for(size_t i = 0; i < sa.GetCount() && !fFound; i++)
1602 if(sa[i] == sr.entry)
1604 sr.segment = segment;
1605 fFound = true;
1609 if(!fFound) m_subrects.RemoveAt(prev);
1613 CRect CScreenLayoutAllocator::AllocRect(CSubtitle* s, int segment, int entry, int layer, int collisions)
1615 // TODO: handle collisions == 1 (reversed collisions)
1616 POSITION pos = m_subrects.GetHeadPosition();
1617 while(pos)
1619 SubRect& sr = m_subrects.GetNext(pos);
1620 if(sr.segment == segment && sr.entry == entry)
1622 return(sr.r + CRect(0, -s->m_topborder, 0, -s->m_bottomborder));
1625 CRect r = s->m_rect + CRect(0, s->m_topborder, 0, s->m_bottomborder);
1626 bool fSearchDown = s->m_scrAlignment > 3;
1627 bool fOK;
1630 fOK = true;
1631 pos = m_subrects.GetHeadPosition();
1632 while(pos)
1634 SubRect& sr = m_subrects.GetNext(pos);
1635 if(layer == sr.layer && !(r & sr.r).IsRectEmpty())
1637 if(fSearchDown)
1639 r.bottom = sr.r.bottom + r.Height();
1640 r.top = sr.r.bottom;
1642 else
1644 r.top = sr.r.top - r.Height();
1645 r.bottom = sr.r.top;
1647 fOK = false;
1651 while(!fOK);
1652 SubRect sr;
1653 sr.r = r;
1654 sr.segment = segment;
1655 sr.entry = entry;
1656 sr.layer = layer;
1657 m_subrects.AddTail(sr);
1658 return(sr.r + CRect(0, -s->m_topborder, 0, -s->m_bottomborder));
1661 // CRenderedTextSubtitle
1663 CAtlMap<CStringW, CRenderedTextSubtitle::AssCmdType, CStringElementTraits<CStringW>> CRenderedTextSubtitle::m_cmdMap;
1665 CRenderedTextSubtitle::CRenderedTextSubtitle(CCritSec* pLock)
1666 : CSubPicProviderImpl(pLock)
1668 if( m_cmdMap.IsEmpty() )
1670 InitCmdMap();
1672 m_size = CSize(0, 0);
1673 if(g_hDC_refcnt == 0)
1675 g_hDC = CreateCompatibleDC(NULL);
1676 SetBkMode(g_hDC, TRANSPARENT);
1677 SetTextColor(g_hDC, 0xffffff);
1678 SetMapMode(g_hDC, MM_TEXT);
1680 g_hDC_refcnt++;
1683 CRenderedTextSubtitle::~CRenderedTextSubtitle()
1685 Deinit();
1686 g_hDC_refcnt--;
1687 if(g_hDC_refcnt == 0) DeleteDC(g_hDC);
1690 void CRenderedTextSubtitle::InitCmdMap()
1692 if( m_cmdMap.IsEmpty() )
1694 m_cmdMap.SetAt(L"1c", CMD_1c);
1695 m_cmdMap.SetAt(L"2c", CMD_2c);
1696 m_cmdMap.SetAt(L"3c", CMD_3c);
1697 m_cmdMap.SetAt(L"4c", CMD_4c);
1698 m_cmdMap.SetAt(L"1a", CMD_1a);
1699 m_cmdMap.SetAt(L"2a", CMD_2a);
1700 m_cmdMap.SetAt(L"3a", CMD_3a);
1701 m_cmdMap.SetAt(L"4a", CMD_4a);
1702 m_cmdMap.SetAt(L"alpha", CMD_alpha);
1703 m_cmdMap.SetAt(L"an", CMD_an);
1704 m_cmdMap.SetAt(L"a", CMD_a);
1705 m_cmdMap.SetAt(L"blur", CMD_blur);
1706 m_cmdMap.SetAt(L"bord", CMD_bord);
1707 m_cmdMap.SetAt(L"be", CMD_be);
1708 m_cmdMap.SetAt(L"b", CMD_b);
1709 m_cmdMap.SetAt(L"clip", CMD_clip);
1710 m_cmdMap.SetAt(L"iclip", CMD_iclip);
1711 m_cmdMap.SetAt(L"c", CMD_c);
1712 m_cmdMap.SetAt(L"fade", CMD_fade);
1713 m_cmdMap.SetAt(L"fad", CMD_fad);
1714 m_cmdMap.SetAt(L"fax", CMD_fax);
1715 m_cmdMap.SetAt(L"fay", CMD_fay);
1716 m_cmdMap.SetAt(L"fe", CMD_fe);
1717 m_cmdMap.SetAt(L"fn", CMD_fn);
1718 m_cmdMap.SetAt(L"frx", CMD_frx);
1719 m_cmdMap.SetAt(L"fry", CMD_fry);
1720 m_cmdMap.SetAt(L"frz", CMD_frz);
1721 m_cmdMap.SetAt(L"fr", CMD_fr);
1722 m_cmdMap.SetAt(L"fscx", CMD_fscx);
1723 m_cmdMap.SetAt(L"fscy", CMD_fscy);
1724 m_cmdMap.SetAt(L"fsc", CMD_fsc);
1725 m_cmdMap.SetAt(L"fsp", CMD_fsp);
1726 m_cmdMap.SetAt(L"fs", CMD_fs);
1727 m_cmdMap.SetAt(L"i", CMD_i);
1728 m_cmdMap.SetAt(L"kt", CMD_kt);
1729 m_cmdMap.SetAt(L"kf", CMD_kf);
1730 m_cmdMap.SetAt(L"K", CMD_K);
1731 m_cmdMap.SetAt(L"ko", CMD_ko);
1732 m_cmdMap.SetAt(L"k", CMD_k);
1733 m_cmdMap.SetAt(L"move", CMD_move);
1734 m_cmdMap.SetAt(L"org", CMD_org);
1735 m_cmdMap.SetAt(L"pbo", CMD_pbo);
1736 m_cmdMap.SetAt(L"pos", CMD_pos);
1737 m_cmdMap.SetAt(L"p", CMD_p);
1738 m_cmdMap.SetAt(L"q", CMD_q);
1739 m_cmdMap.SetAt(L"r", CMD_r);
1740 m_cmdMap.SetAt(L"shad", CMD_shad);
1741 m_cmdMap.SetAt(L"s", CMD_s);
1742 m_cmdMap.SetAt(L"t", CMD_t);
1743 m_cmdMap.SetAt(L"u", CMD_u);
1744 m_cmdMap.SetAt(L"xbord", CMD_xbord);
1745 m_cmdMap.SetAt(L"xshad", CMD_xshad);
1746 m_cmdMap.SetAt(L"ybord", CMD_ybord);
1747 m_cmdMap.SetAt(L"yshad", CMD_yshad);
1751 void CRenderedTextSubtitle::Copy(CRenderedTextSubtitle& rts)
1753 __super::Copy(rts);
1754 m_size = rts.m_size;
1757 void CRenderedTextSubtitle::Copy(CSimpleTextSubtitle& sts)
1759 __super::Copy(sts);
1762 void CRenderedTextSubtitle::Empty()
1764 Deinit();
1765 __super::Empty();
1768 void CRenderedTextSubtitle::OnChanged()
1770 __super::OnChanged();
1771 POSITION pos = m_subtitleCache.GetStartPosition();
1772 while(pos)
1774 int i;
1775 CSubtitle* s;
1776 m_subtitleCache.GetNextAssoc(pos, i, s);
1777 delete s;
1779 m_subtitleCache.RemoveAll();
1780 m_sla.Empty();
1783 bool CRenderedTextSubtitle::Init(CSize size, CRect vidrect)
1785 Deinit();
1786 m_size = CSize(size.cx*8, size.cy*8);
1787 m_vidrect = CRect(vidrect.left*8, vidrect.top*8, vidrect.right*8, vidrect.bottom*8);
1788 m_sla.Empty();
1789 return(true);
1792 void CRenderedTextSubtitle::Deinit()
1794 POSITION pos = m_subtitleCache.GetStartPosition();
1795 while(pos)
1797 int i;
1798 CSubtitle* s;
1799 m_subtitleCache.GetNextAssoc(pos, i, s);
1800 delete s;
1802 m_subtitleCache.RemoveAll();
1803 m_sla.Empty();
1804 m_size = CSize(0, 0);
1805 m_vidrect.SetRectEmpty();
1807 CacheManager::GetCWordMruCache()->clear();
1808 CacheManager::GetPathDataMruCache()->clear();
1809 CacheManager::GetScanLineDataMruCache()->clear();
1810 CacheManager::GetOverlayNoBlurMruCache()->clear();
1811 CacheManager::GetOverlayMruCache()->clear();
1814 void CRenderedTextSubtitle::ParseEffect(CSubtitle* sub, const CStringW& str)
1816 CStringW::PCXSTR str_start = str.GetString();
1817 CStringW::PCXSTR str_end = str_start + str.GetLength();
1818 str_start = SkipWhiteSpaceLeft(str_start, str_end);
1820 if(!sub || *str_start==0)
1821 return;
1823 str_end = FastSkipWhiteSpaceRight(str_start, str_end);
1825 const WCHAR* s = FindChar(str_start, str_end, L';');
1826 if(*s==L';') {
1827 s++;
1830 const CStringW effect(str_start, s-str_start);
1831 if(!effect.CompareNoCase( L"Banner;" ) )
1833 int delay, lefttoright = 0, fadeawaywidth = 0;
1834 if(swscanf(s, L"%d;%d;%d", &delay, &lefttoright, &fadeawaywidth) < 1) return;
1835 Effect* e = new Effect;
1836 if(!e) return;
1837 sub->m_effects[e->type = EF_BANNER] = e;
1838 e->param[0] = (int)(max(1.0*delay/sub->m_scalex, 1));
1839 e->param[1] = lefttoright;
1840 e->param[2] = (int)(sub->m_scalex*fadeawaywidth);
1841 sub->m_wrapStyle = 2;
1843 else if(!effect.CompareNoCase(L"Scroll up;") || !effect.CompareNoCase(L"Scroll down;"))
1845 int top, bottom, delay, fadeawayheight = 0;
1846 if(swscanf(s, L"%d;%d;%d;%d", &top, &bottom, &delay, &fadeawayheight) < 3) return;
1847 if(top > bottom) {int tmp = top; top = bottom; bottom = tmp;}
1848 Effect* e = new Effect;
1849 if(!e) return;
1850 sub->m_effects[e->type = EF_SCROLL] = e;
1851 e->param[0] = (int)(sub->m_scaley*top*8);
1852 e->param[1] = (int)(sub->m_scaley*bottom*8);
1853 e->param[2] = (int)(max(1.0*delay/sub->m_scaley, 1));
1854 e->param[3] = (effect.GetLength() == 12);
1855 e->param[4] = (int)(sub->m_scaley*fadeawayheight);
1859 void CRenderedTextSubtitle::ParseString(CSubtitle* sub, CStringW str, const FwSTSStyle& style)
1861 if(!sub) return;
1862 str.Replace(L"\\N", L"\n");
1863 str.Replace(L"\\n", (sub->m_wrapStyle < 2 || sub->m_wrapStyle == 3) ? L" " : L"\n");
1864 str.Replace(L"\\h", L"\x00A0");
1865 CWordMruCache* word_mru_cache=CacheManager::GetCWordMruCache();
1866 for(int ite = 0, j = 0, len = str.GetLength(); j <= len; j++)
1868 WCHAR c = str[j];
1869 if(c != L'\n' && c != L' ' && c != L'\x00A0' && c != 0)
1870 continue;
1871 if(ite < j)
1873 CWordCacheKey word_cache_key(style, str.Mid(ite, j-ite), m_ktype, m_kstart, m_kend);
1874 CWordMruCache::hashed_cache_const_iterator iter = word_mru_cache->hash_find(word_cache_key);
1875 if( iter != word_mru_cache->hash_end() )
1877 sub->m_words.AddTail(iter->word);
1879 else if(PCWord tmp_ptr = new CText(style, str.Mid(ite, j-ite), m_ktype, m_kstart, m_kend))
1881 SharedPtrCWord w(tmp_ptr);
1882 sub->m_words.AddTail(w);
1883 CWordMruItem item(word_cache_key, w);
1884 word_mru_cache->update_cache(item);
1886 else
1888 ///TODO: overflow handling
1890 m_kstart = m_kend;
1892 if(c == L'\n')
1894 CWordCacheKey word_cache_key(style, CStringW(), m_ktype, m_kstart, m_kend);
1895 CWordMruCache::hashed_cache_const_iterator iter = word_mru_cache->hash_find(word_cache_key);
1896 if( iter != word_mru_cache->hash_end() )
1898 sub->m_words.AddTail(iter->word);
1900 else if(PCWord tmp_ptr = new CText(style, CStringW(), m_ktype, m_kstart, m_kend))
1902 SharedPtrCWord w(tmp_ptr);
1903 sub->m_words.AddTail(w);
1904 CWordMruItem item(word_cache_key, w);
1905 word_mru_cache->update_cache(item);
1907 else
1909 ///TODO: overflow handling
1911 m_kstart = m_kend;
1913 else if(c == L' ' || c == L'\x00A0')
1915 CWordCacheKey word_cache_key(style, CStringW(c), m_ktype, m_kstart, m_kend);
1916 CWordMruCache::hashed_cache_const_iterator iter = word_mru_cache->hash_find(word_cache_key);
1917 if( iter != word_mru_cache->hash_end() )
1919 sub->m_words.AddTail(iter->word);
1921 else if(PCWord tmp_ptr = new CText(style, CStringW(c), m_ktype, m_kstart, m_kend))
1923 SharedPtrCWord w(tmp_ptr);
1924 sub->m_words.AddTail(w);
1925 CWordMruItem item(word_cache_key, w);
1926 word_mru_cache->update_cache(item);
1928 else
1930 ///TODO: overflow handling
1932 m_kstart = m_kend;
1934 ite = j+1;
1936 return;
1939 void CRenderedTextSubtitle::ParsePolygon(CSubtitle* sub, const CStringW& str, const FwSTSStyle& style)
1941 if(!sub || !str.GetLength() || !m_nPolygon) return;
1943 if(PCWord tmp_ptr = new CPolygon(style, str, m_ktype, m_kstart, m_kend, sub->m_scalex/(1<<(m_nPolygon-1)), sub->m_scaley/(1<<(m_nPolygon-1)), m_polygonBaselineOffset))
1945 SharedPtrCWord w(tmp_ptr);
1946 ///Todo: fix me
1947 //if( PCWord w_cache = m_wordCache.lookup(*w) )
1949 // sub->m_words.AddTail(w_cache);
1950 // delete w;
1952 //else
1954 sub->m_words.AddTail(w);
1956 m_kstart = m_kend;
1960 bool CRenderedTextSubtitle::ParseSSATag(CSubtitle* sub, const CStringW& str, STSStyle& style, const STSStyle& org, bool fAnimate)
1962 if(!sub) return(false);
1963 int nTags = 0, nUnrecognizedTags = 0;
1964 for(int i = 0, j; (j = str.Find(L'\\', i)) >= 0; i = j)
1966 j++;
1967 CStringW::PCXSTR str_start = str.GetString() + j;
1968 CStringW::PCXSTR pc = str_start;
1969 while( iswspace(*pc) )
1971 pc++;
1973 j += pc-str_start;
1974 str_start = pc;
1975 while( *pc && *pc != L'(' && *pc != L'\\' )
1977 pc++;
1979 j += pc-str_start;
1980 if( pc-str_start>0 )
1982 while( iswspace(*--pc) );
1983 pc++;
1986 const CStringW cmd(str_start, pc-str_start);
1987 if(cmd.IsEmpty()) continue;
1989 CAtlArray<CStringW> params;
1990 if(str[j] == L'(')
1992 j++;
1993 CStringW::PCXSTR str_start = str.GetString() + j;
1994 CStringW::PCXSTR pc = str_start;
1995 while( iswspace(*pc) )
1997 pc++;
1999 j += pc-str_start;
2000 str_start = pc;
2001 while( *pc && *pc != L')' )
2003 pc++;
2005 j += pc-str_start;
2006 if( pc-str_start>0 )
2008 while( iswspace(*--pc) );
2009 pc++;
2012 CStringW::PCXSTR param_start = str_start;
2013 CStringW::PCXSTR param_end = pc;
2014 while( param_start<param_end )
2016 param_start = SkipWhiteSpaceLeft(param_start, param_end);
2018 CStringW::PCXSTR newstart = FindChar(param_start, param_end, L',');
2019 CStringW::PCXSTR newend = FindChar(param_start, param_end, L'\\');
2020 if(newstart > param_start && newstart < newend)
2022 newstart = FastSkipWhiteSpaceRight(param_start, newstart);
2023 CStringW s(param_start, newstart - param_start);
2025 if(!s.IsEmpty()) params.Add(s);
2026 param_start = newstart + 1;
2028 else if(param_start<param_end)
2030 CStringW s(param_start, param_end - param_start);
2032 params.Add(s);
2033 param_start = param_end;
2038 AssCmdType cmd_type = CMD_COUNT;
2039 int cmd_length = min(MAX_CMD_LENGTH, cmd.GetLength());
2040 for( ;cmd_length>=MIN_CMD_LENGTH;cmd_length-- )
2042 if( m_cmdMap.Lookup(cmd.Left(cmd_length), cmd_type) )
2043 break;
2045 if(cmd_length<MIN_CMD_LENGTH)
2046 cmd_type = CMD_COUNT;
2047 switch( cmd_type )
2049 case CMD_fax:
2050 case CMD_fay:
2051 case CMD_fe:
2052 case CMD_fn:
2053 case CMD_frx:
2054 case CMD_fry:
2055 case CMD_frz:
2056 case CMD_fr:
2057 case CMD_fscx:
2058 case CMD_fscy:
2059 case CMD_fsc:
2060 case CMD_fsp:
2061 case CMD_fs:
2062 case CMD_i:
2063 case CMD_kt:
2064 case CMD_kf:
2065 case CMD_K:
2066 case CMD_ko:
2067 case CMD_k:
2068 case CMD_pbo:
2069 case CMD_p:
2070 case CMD_q:
2071 case CMD_r:
2072 case CMD_shad:
2073 case CMD_s:
2074 case CMD_an:
2075 case CMD_a:
2076 case CMD_blur:
2077 case CMD_bord:
2078 case CMD_be:
2079 case CMD_b:
2080 case CMD_u:
2081 case CMD_xbord:
2082 case CMD_xshad:
2083 case CMD_ybord:
2084 case CMD_yshad:
2085 // default:
2086 params.Add(cmd.Mid(cmd_length));
2087 break;
2088 case CMD_c:
2089 case CMD_1c :
2090 case CMD_2c :
2091 case CMD_3c :
2092 case CMD_4c :
2093 case CMD_1a :
2094 case CMD_2a :
2095 case CMD_3a :
2096 case CMD_4a :
2097 case CMD_alpha:
2098 params.Add(cmd.Mid(cmd_length).Trim(L"&H"));
2099 break;
2100 case CMD_clip:
2101 case CMD_iclip:
2102 case CMD_fade:
2103 case CMD_fad:
2104 case CMD_move:
2105 case CMD_org:
2106 case CMD_pos:
2107 case CMD_t:
2108 break;
2109 case CMD_COUNT:
2110 nUnrecognizedTags++;
2111 break;
2113 nTags++;
2114 // TODO: call ParseStyleModifier(cmd, params, ..) and move the rest there
2115 const CStringW& p = params.GetCount() > 0 ? params[0] : CStringW("");
2116 switch ( cmd_type )
2118 case CMD_1c :
2119 case CMD_2c :
2120 case CMD_3c :
2121 case CMD_4c :
2123 int i = cmd[0] - L'1';
2124 DWORD c = wcstol(p, NULL, 16);
2125 style.colors[i] = !p.IsEmpty()
2126 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2127 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2128 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2129 : org.colors[i];
2130 break;
2132 case CMD_1a :
2133 case CMD_2a :
2134 case CMD_3a :
2135 case CMD_4a :
2137 int i = cmd[0] - L'1';
2138 style.alpha[i] = !p.IsEmpty()
2139 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2140 : org.alpha[i];
2141 break;
2143 case CMD_alpha:
2145 for(int i = 0; i < 4; i++)
2147 style.alpha[i] = !p.IsEmpty()
2148 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2149 : org.alpha[i];
2151 break;
2153 case CMD_an:
2155 int n = wcstol(p, NULL, 10);
2156 if(sub->m_scrAlignment < 0)
2157 sub->m_scrAlignment = (n > 0 && n < 10) ? n : org.scrAlignment;
2158 break;
2160 case CMD_a:
2162 int n = wcstol(p, NULL, 10);
2163 if(sub->m_scrAlignment < 0)
2164 sub->m_scrAlignment = (n > 0 && n < 12) ? ((((n-1)&3)+1)+((n&4)?6:0)+((n&8)?3:0)) : org.scrAlignment;
2165 break;
2167 case CMD_blur:
2169 double n = CalcAnimation(wcstod(p, NULL), style.fGaussianBlur, fAnimate);
2170 style.fGaussianBlur = !p.IsEmpty()
2171 ? (n < 0 ? 0 : n)
2172 : org.fGaussianBlur;
2173 break;
2175 case CMD_bord:
2177 double dst = wcstod(p, NULL);
2178 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2179 style.outlineWidthX = !p.IsEmpty()
2180 ? (nx < 0 ? 0 : nx)
2181 : org.outlineWidthX;
2182 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2183 style.outlineWidthY = !p.IsEmpty()
2184 ? (ny < 0 ? 0 : ny)
2185 : org.outlineWidthY;
2186 break;
2188 case CMD_be:
2190 int n = (int)(CalcAnimation(wcstol(p, NULL, 10), style.fBlur, fAnimate)+0.5);
2191 style.fBlur = !p.IsEmpty()
2193 : org.fBlur;
2194 break;
2196 case CMD_b:
2198 int n = wcstol(p, NULL, 10);
2199 style.fontWeight = !p.IsEmpty()
2200 ? (n == 0 ? FW_NORMAL : n == 1 ? FW_BOLD : n >= 100 ? n : org.fontWeight)
2201 : org.fontWeight;
2202 break;
2204 case CMD_clip:
2205 case CMD_iclip:
2207 bool invert = (cmd_type == CMD_iclip);
2208 if(params.GetCount() == 1 && !sub->m_pClipper)
2210 sub->m_pClipper = new CClipper(params[0], CSize(m_size.cx>>3, m_size.cy>>3), sub->m_scalex, sub->m_scaley, invert);
2212 else if(params.GetCount() == 2 && !sub->m_pClipper)
2214 int scale = max(wcstol(p, NULL, 10), 1);
2215 sub->m_pClipper = new CClipper(params[1], CSize(m_size.cx>>3, m_size.cy>>3), sub->m_scalex/(1<<(scale-1)), sub->m_scaley/(1<<(scale-1)), invert);
2217 else if(params.GetCount() == 4)
2219 CRect r;
2220 sub->m_clipInverse = invert;
2221 r.SetRect(
2222 wcstol(params[0], NULL, 10),
2223 wcstol(params[1], NULL, 10),
2224 wcstol(params[2], NULL, 10),
2225 wcstol(params[3], NULL, 10));
2226 CPoint o(0, 0);
2227 if(sub->m_relativeTo == 1) // TODO: this should also apply to the other two clippings above
2229 o.x = m_vidrect.left>>3;
2230 o.y = m_vidrect.top>>3;
2232 sub->m_clip.SetRect(
2233 (int)CalcAnimation(sub->m_scalex*r.left + o.x, sub->m_clip.left, fAnimate),
2234 (int)CalcAnimation(sub->m_scaley*r.top + o.y, sub->m_clip.top, fAnimate),
2235 (int)CalcAnimation(sub->m_scalex*r.right + o.x, sub->m_clip.right, fAnimate),
2236 (int)CalcAnimation(sub->m_scaley*r.bottom + o.y, sub->m_clip.bottom, fAnimate));
2238 break;
2240 case CMD_c:
2242 DWORD c = wcstol(p, NULL, 16);
2243 style.colors[0] = !p.IsEmpty()
2244 ? (((int)CalcAnimation(c&0xff, style.colors[0]&0xff, fAnimate))&0xff
2245 |((int)CalcAnimation(c&0xff00, style.colors[0]&0xff00, fAnimate))&0xff00
2246 |((int)CalcAnimation(c&0xff0000, style.colors[0]&0xff0000, fAnimate))&0xff0000)
2247 : org.colors[0];
2248 break;
2250 case CMD_fade:
2251 case CMD_fad:
2253 if(params.GetCount() == 7 && !sub->m_effects[EF_FADE])// {\fade(a1=param[0], a2=param[1], a3=param[2], t1=t[0], t2=t[1], t3=t[2], t4=t[3])
2255 if(Effect* e = new Effect)
2257 for(int i = 0; i < 3; i++)
2258 e->param[i] = wcstol(params[i], NULL, 10);
2259 for(int i = 0; i < 4; i++)
2260 e->t[i] = wcstol(params[3+i], NULL, 10);
2261 sub->m_effects[EF_FADE] = e;
2264 else if(params.GetCount() == 2 && !sub->m_effects[EF_FADE]) // {\fad(t1=t[1], t2=t[2])
2266 if(Effect* e = new Effect)
2268 e->param[0] = e->param[2] = 0xff;
2269 e->param[1] = 0x00;
2270 for(int i = 1; i < 3; i++)
2271 e->t[i] = wcstol(params[i-1], NULL, 10);
2272 e->t[0] = e->t[3] = -1; // will be substituted with "start" and "end"
2273 sub->m_effects[EF_FADE] = e;
2276 break;
2278 case CMD_fax:
2280 style.fontShiftX = !p.IsEmpty()
2281 ? CalcAnimation(wcstod(p, NULL), style.fontShiftX, fAnimate)
2282 : org.fontShiftX;
2283 break;
2285 case CMD_fay:
2287 style.fontShiftY = !p.IsEmpty()
2288 ? CalcAnimation(wcstod(p, NULL), style.fontShiftY, fAnimate)
2289 : org.fontShiftY;
2290 break;
2292 case CMD_fe:
2294 int n = wcstol(p, NULL, 10);
2295 style.charSet = !p.IsEmpty()
2297 : org.charSet;
2298 break;
2300 case CMD_fn:
2302 if(!p.IsEmpty() && p != L'0')
2303 style.fontName = CString(p).Trim();
2304 else
2305 style.fontName = org.fontName;
2306 break;
2308 case CMD_frx:
2310 style.fontAngleX = !p.IsEmpty()
2311 ? CalcAnimation(wcstod(p, NULL), style.fontAngleX, fAnimate)
2312 : org.fontAngleX;
2313 break;
2315 case CMD_fry:
2317 style.fontAngleY = !p.IsEmpty()
2318 ? CalcAnimation(wcstod(p, NULL), style.fontAngleY, fAnimate)
2319 : org.fontAngleY;
2320 break;
2322 case CMD_frz:
2323 case CMD_fr:
2325 style.fontAngleZ = !p.IsEmpty()
2326 ? CalcAnimation(wcstod(p, NULL), style.fontAngleZ, fAnimate)
2327 : org.fontAngleZ;
2328 break;
2330 case CMD_fscx:
2332 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontScaleX, fAnimate);
2333 style.fontScaleX = !p.IsEmpty()
2334 ? ((n < 0) ? 0 : n)
2335 : org.fontScaleX;
2336 break;
2338 case CMD_fscy:
2340 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontScaleY, fAnimate);
2341 style.fontScaleY = !p.IsEmpty()
2342 ? ((n < 0) ? 0 : n)
2343 : org.fontScaleY;
2344 break;
2346 case CMD_fsc:
2348 style.fontScaleX = org.fontScaleX;
2349 style.fontScaleY = org.fontScaleY;
2350 break;
2352 case CMD_fsp:
2354 style.fontSpacing = !p.IsEmpty()
2355 ? CalcAnimation(wcstod(p, NULL), style.fontSpacing, fAnimate)
2356 : org.fontSpacing;
2357 break;
2359 case CMD_fs:
2361 if(!p.IsEmpty())
2363 if(p[0] == L'-' || p[0] == L'+')
2365 double n = CalcAnimation(style.fontSize + style.fontSize*wcstol(p, NULL, 10)/10, style.fontSize, fAnimate);
2366 style.fontSize = (n > 0) ? n : org.fontSize;
2368 else
2370 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontSize, fAnimate);
2371 style.fontSize = (n > 0) ? n : org.fontSize;
2374 else
2376 style.fontSize = org.fontSize;
2378 break;
2380 case CMD_i:
2382 int n = wcstol(p, NULL, 10);
2383 style.fItalic = !p.IsEmpty()
2384 ? (n == 0 ? false : n == 1 ? true : org.fItalic)
2385 : org.fItalic;
2386 break;
2388 case CMD_kt:
2390 m_kstart = !p.IsEmpty()
2391 ? wcstol(p, NULL, 10)*10
2392 : 0;
2393 m_kend = m_kstart;
2394 break;
2395 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2397 case CMD_kf:
2398 case CMD_K:
2400 m_ktype = 1;
2401 m_kstart = m_kend;
2402 m_kend += !p.IsEmpty()
2403 ? wcstol(p, NULL, 10)*10
2404 : 1000;
2405 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2406 break;
2408 case CMD_ko:
2410 m_ktype = 2;
2411 m_kstart = m_kend;
2412 m_kend += !p.IsEmpty()
2413 ? wcstol(p, NULL, 10)*10
2414 : 1000;
2415 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2416 break;
2418 case CMD_k:
2420 m_ktype = 0;
2421 m_kstart = m_kend;
2422 m_kend += !p.IsEmpty()
2423 ? wcstol(p, NULL, 10)*10
2424 : 1000;
2425 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2426 break;
2428 case CMD_move: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3][, t1=t[0], t2=t[1]])}
2430 if((params.GetCount() == 4 || params.GetCount() == 6) && !sub->m_effects[EF_MOVE])
2432 if(Effect* e = new Effect)
2434 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2435 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2436 e->param[2] = (int)(sub->m_scalex*wcstod(params[2], NULL)*8);
2437 e->param[3] = (int)(sub->m_scaley*wcstod(params[3], NULL)*8);
2438 e->t[0] = e->t[1] = -1;
2439 if(params.GetCount() == 6)
2441 for(int i = 0; i < 2; i++)
2442 e->t[i] = wcstol(params[4+i], NULL, 10);
2444 sub->m_effects[EF_MOVE] = e;
2447 break;
2449 case CMD_org: // {\org(x=param[0], y=param[1])}
2451 if(params.GetCount() == 2 && !sub->m_effects[EF_ORG])
2453 if(Effect* e = new Effect)
2455 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2456 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2457 sub->m_effects[EF_ORG] = e;
2460 break;
2462 case CMD_pbo:
2464 m_polygonBaselineOffset = wcstol(p, NULL, 10);
2465 break;
2467 case CMD_pos:
2469 if(params.GetCount() == 2 && !sub->m_effects[EF_MOVE])
2471 if(Effect* e = new Effect)
2473 e->param[0] = e->param[2] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2474 e->param[1] = e->param[3] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2475 e->t[0] = e->t[1] = 0;
2476 sub->m_effects[EF_MOVE] = e;
2479 break;
2481 case CMD_p:
2483 int n = wcstol(p, NULL, 10);
2484 m_nPolygon = (n <= 0 ? 0 : n);
2485 break;
2487 case CMD_q:
2489 int n = wcstol(p, NULL, 10);
2490 sub->m_wrapStyle = !p.IsEmpty() && (0 <= n && n <= 3)
2492 : m_defaultWrapStyle;
2493 break;
2495 case CMD_r:
2497 STSStyle* val;
2498 style = (!p.IsEmpty() && m_styles.Lookup(WToT(p), val) && val) ? *val : org;
2499 break;
2501 case CMD_shad:
2503 double dst = wcstod(p, NULL);
2504 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2505 style.shadowDepthX = !p.IsEmpty()
2506 ? (nx < 0 ? 0 : nx)
2507 : org.shadowDepthX;
2508 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2509 style.shadowDepthY = !p.IsEmpty()
2510 ? (ny < 0 ? 0 : ny)
2511 : org.shadowDepthY;
2512 break;
2514 case CMD_s:
2516 int n = wcstol(p, NULL, 10);
2517 style.fStrikeOut = !p.IsEmpty()
2518 ? (n == 0 ? false : n == 1 ? true : org.fStrikeOut)
2519 : org.fStrikeOut;
2520 break;
2522 case CMD_t: // \t([<t1>,<t2>,][<accel>,]<style modifiers>)
2524 CStringW param;
2525 m_animStart = m_animEnd = 0;
2526 m_animAccel = 1;
2527 if(params.GetCount() == 1)
2529 param = params[0];
2531 else if(params.GetCount() == 2)
2533 m_animAccel = wcstod(params[0], NULL);
2534 param = params[1];
2536 else if(params.GetCount() == 3)
2538 m_animStart = (int)wcstod(params[0], NULL);
2539 m_animEnd = (int)wcstod(params[1], NULL);
2540 param = params[2];
2542 else if(params.GetCount() == 4)
2544 m_animStart = wcstol(params[0], NULL, 10);
2545 m_animEnd = wcstol(params[1], NULL, 10);
2546 m_animAccel = wcstod(params[2], NULL);
2547 param = params[3];
2549 ParseSSATag(sub, param, style, org, true);
2550 sub->m_fAnimated = true;
2551 break;
2553 case CMD_u:
2555 int n = wcstol(p, NULL, 10);
2556 style.fUnderline = !p.IsEmpty()
2557 ? (n == 0 ? false : n == 1 ? true : org.fUnderline)
2558 : org.fUnderline;
2559 break;
2561 case CMD_xbord:
2563 double dst = wcstod(p, NULL);
2564 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2565 style.outlineWidthX = !p.IsEmpty()
2566 ? (nx < 0 ? 0 : nx)
2567 : org.outlineWidthX;
2568 break;
2570 case CMD_xshad:
2572 double dst = wcstod(p, NULL);
2573 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2574 style.shadowDepthX = !p.IsEmpty()
2575 ? nx
2576 : org.shadowDepthX;
2577 break;
2579 case CMD_ybord:
2581 double dst = wcstod(p, NULL);
2582 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2583 style.outlineWidthY = !p.IsEmpty()
2584 ? (ny < 0 ? 0 : ny)
2585 : org.outlineWidthY;
2586 break;
2588 case CMD_yshad:
2590 double dst = wcstod(p, NULL);
2591 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2592 style.shadowDepthY = !p.IsEmpty()
2593 ? ny
2594 : org.shadowDepthY;
2595 break;
2597 default:
2598 break;
2601 // return(nUnrecognizedTags < nTags);
2602 return(true); // there are ppl keeping coments inside {}, lets make them happy now
2605 bool CRenderedTextSubtitle::ParseHtmlTag(CSubtitle* sub, CStringW str, STSStyle& style, STSStyle& org)
2607 if(str.Find(L"!--") == 0)
2608 return(true);
2609 bool fClosing = str[0] == L'/';
2610 str.Trim(L" /");
2611 int i = str.Find(L' ');
2612 if(i < 0) i = str.GetLength();
2613 CStringW tag = str.Left(i).MakeLower();
2614 str = str.Mid(i).Trim();
2615 CAtlArray<CStringW> attribs, params;
2616 while((i = str.Find(L'=')) > 0)
2618 attribs.Add(str.Left(i).Trim().MakeLower());
2619 str = str.Mid(i+1);
2620 for(i = 0; _istspace(str[i]); i++);
2621 str = str.Mid(i);
2622 if(str[0] == L'\"') {str = str.Mid(1); i = str.Find(L'\"');}
2623 else i = str.Find(L' ');
2624 if(i < 0) i = str.GetLength();
2625 params.Add(str.Left(i).Trim().MakeLower());
2626 str = str.Mid(i+1);
2628 if(tag == L"text")
2630 else if(tag == L"b" || tag == L"strong")
2631 style.fontWeight = !fClosing ? FW_BOLD : org.fontWeight;
2632 else if(tag == L"i" || tag == L"em")
2633 style.fItalic = !fClosing ? true : org.fItalic;
2634 else if(tag == L"u")
2635 style.fUnderline = !fClosing ? true : org.fUnderline;
2636 else if(tag == L"s" || tag == L"strike" || tag == L"del")
2637 style.fStrikeOut = !fClosing ? true : org.fStrikeOut;
2638 else if(tag == L"font")
2640 if(!fClosing)
2642 for(size_t i = 0; i < attribs.GetCount(); i++)
2644 if(params[i].IsEmpty()) continue;
2645 int nColor = -1;
2646 if(attribs[i] == L"face")
2648 style.fontName = params[i];
2650 else if(attribs[i] == L"size")
2652 if(params[i][0] == L'+')
2653 style.fontSize += wcstol(params[i], NULL, 10);
2654 else if(params[i][0] == L'-')
2655 style.fontSize -= wcstol(params[i], NULL, 10);
2656 else
2657 style.fontSize = wcstol(params[i], NULL, 10);
2659 else if(attribs[i] == L"color")
2661 nColor = 0;
2663 else if(attribs[i] == L"outline-color")
2665 nColor = 2;
2667 else if(attribs[i] == L"outline-level")
2669 style.outlineWidthX = style.outlineWidthY = wcstol(params[i], NULL, 10);
2671 else if(attribs[i] == L"shadow-color")
2673 nColor = 3;
2675 else if(attribs[i] == L"shadow-level")
2677 style.shadowDepthX = style.shadowDepthY = wcstol(params[i], NULL, 10);
2679 if(nColor >= 0 && nColor < 4)
2681 CString key = WToT(params[i]).TrimLeft(L'#');
2682 DWORD val;
2683 if(g_colors.Lookup(key, val))
2684 style.colors[nColor] = val;
2685 else if((style.colors[nColor] = _tcstol(key, NULL, 16)) == 0)
2686 style.colors[nColor] = 0x00ffffff; // default is white
2687 style.colors[nColor] = ((style.colors[nColor]>>16)&0xff)|((style.colors[nColor]&0xff)<<16)|(style.colors[nColor]&0x00ff00);
2691 else
2693 style.fontName = org.fontName;
2694 style.fontSize = org.fontSize;
2695 memcpy(style.colors, org.colors, sizeof(style.colors));
2698 else if(tag == L"k" && attribs.GetCount() == 1 && attribs[0] == L"t")
2700 m_ktype = 1;
2701 m_kstart = m_kend;
2702 m_kend += wcstol(params[0], NULL, 10);
2704 else
2705 return(false);
2706 return(true);
2709 double CRenderedTextSubtitle::CalcAnimation(double dst, double src, bool fAnimate)
2711 int s = m_animStart ? m_animStart : 0;
2712 int e = m_animEnd ? m_animEnd : m_delay;
2713 if(fabs(dst-src) >= 0.0001 && fAnimate)
2715 if(m_time < s) dst = src;
2716 else if(s <= m_time && m_time < e)
2718 double t = pow(1.0 * (m_time - s) / (e - s), m_animAccel);
2719 dst = (1 - t) * src + t * dst;
2721 // else dst = dst;
2723 return(dst);
2726 CSubtitle* CRenderedTextSubtitle::GetSubtitle(int entry)
2728 CSubtitle* sub;
2729 if(m_subtitleCache.Lookup(entry, sub))
2731 if(sub->m_fAnimated) {delete sub; sub = NULL;}
2732 else return(sub);
2734 sub = new CSubtitle();
2735 if(!sub) return(NULL);
2736 CStringW str = GetStrW(entry, true);
2737 STSStyle stss, orgstss;
2738 GetStyle(entry, &stss);
2739 if (stss.fontScaleX == stss.fontScaleY && m_dPARCompensation != 1.0)
2741 switch(m_ePARCompensationType)
2743 case EPCTUpscale:
2744 if (m_dPARCompensation < 1.0)
2745 stss.fontScaleY /= m_dPARCompensation;
2746 else
2747 stss.fontScaleX *= m_dPARCompensation;
2748 break;
2749 case EPCTDownscale:
2750 if (m_dPARCompensation < 1.0)
2751 stss.fontScaleX *= m_dPARCompensation;
2752 else
2753 stss.fontScaleY /= m_dPARCompensation;
2754 break;
2755 case EPCTAccurateSize:
2756 stss.fontScaleX *= m_dPARCompensation;
2757 break;
2760 orgstss = stss;
2761 sub->m_clip.SetRect(0, 0, m_size.cx>>3, m_size.cy>>3);
2762 sub->m_scrAlignment = -stss.scrAlignment;
2763 sub->m_wrapStyle = m_defaultWrapStyle;
2764 sub->m_fAnimated = false;
2765 sub->m_relativeTo = stss.relativeTo;
2766 sub->m_scalex = m_dstScreenSize.cx > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Width() : m_size.cx) / (m_dstScreenSize.cx*8) : 1.0;
2767 sub->m_scaley = m_dstScreenSize.cy > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Height() : m_size.cy) / (m_dstScreenSize.cy*8) : 1.0;
2768 m_animStart = m_animEnd = 0;
2769 m_animAccel = 1;
2770 m_ktype = m_kstart = m_kend = 0;
2771 m_nPolygon = 0;
2772 m_polygonBaselineOffset = 0;
2773 ParseEffect(sub, m_entries.GetAt(entry).effect);
2774 while(!str.IsEmpty())
2776 bool fParsed = false;
2777 int i;
2778 if(str[0] == L'{' && (i = str.Find(L'}')) > 0)
2780 if(fParsed = ParseSSATag(sub, str.Mid(1, i-1), stss, orgstss))
2781 str = str.Mid(i+1);
2783 else if(str[0] == L'<' && (i = str.Find(L'>')) > 0)
2785 if(fParsed = ParseHtmlTag(sub, str.Mid(1, i-1), stss, orgstss))
2786 str = str.Mid(i+1);
2788 if(fParsed)
2790 i = str.FindOneOf(L"{<");
2791 if(i < 0) i = str.GetLength();
2792 if(i == 0) continue;
2794 else
2796 i = str.Mid(1).FindOneOf(L"{<");
2797 if(i < 0) i = str.GetLength()-1;
2798 i++;
2800 STSStyle tmp = stss;
2801 tmp.fontSize = sub->m_scaley*tmp.fontSize*64;
2802 tmp.fontSpacing = sub->m_scalex*tmp.fontSpacing*64;
2803 tmp.outlineWidthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2804 tmp.outlineWidthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2805 tmp.shadowDepthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2806 tmp.shadowDepthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2807 FwSTSStyle fw_tmp(tmp);
2808 if(m_nPolygon)
2810 ParsePolygon(sub, str.Left(i), fw_tmp);
2812 else
2814 ParseString(sub, str.Left(i), fw_tmp);
2816 str = str.Mid(i);
2818 sub->m_fAnimated2 |= sub->m_fAnimated;
2819 if( sub->m_effects[EF_FADE] || sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL]
2820 || sub->m_effects[EF_MOVE] )
2821 sub->m_fAnimated2 = true;
2822 // just a "work-around" solution... in most cases nobody will want to use \org together with moving but without rotating the subs
2823 if(sub->m_effects[EF_ORG] && (sub->m_effects[EF_MOVE] || sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL]))
2824 sub->m_fAnimated = true;
2825 sub->m_scrAlignment = abs(sub->m_scrAlignment);
2826 STSEntry stse = m_entries.GetAt(entry);
2827 CRect marginRect = stse.marginRect;
2828 if(marginRect.left == 0) marginRect.left = orgstss.marginRect.get().left;
2829 if(marginRect.top == 0) marginRect.top = orgstss.marginRect.get().top;
2830 if(marginRect.right == 0) marginRect.right = orgstss.marginRect.get().right;
2831 if(marginRect.bottom == 0) marginRect.bottom = orgstss.marginRect.get().bottom;
2832 marginRect.left = (int)(sub->m_scalex*marginRect.left*8);
2833 marginRect.top = (int)(sub->m_scaley*marginRect.top*8);
2834 marginRect.right = (int)(sub->m_scalex*marginRect.right*8);
2835 marginRect.bottom = (int)(sub->m_scaley*marginRect.bottom*8);
2836 if(stss.relativeTo == 1)
2838 marginRect.left += m_vidrect.left;
2839 marginRect.top += m_vidrect.top;
2840 marginRect.right += m_size.cx - m_vidrect.right;
2841 marginRect.bottom += m_size.cy - m_vidrect.bottom;
2843 sub->CreateClippers(m_size);
2844 sub->MakeLines(m_size, marginRect);
2845 m_subtitleCache[entry] = sub;
2846 return(sub);
2851 STDMETHODIMP CRenderedTextSubtitle::NonDelegatingQueryInterface(REFIID riid, void** ppv)
2853 CheckPointer(ppv, E_POINTER);
2854 *ppv = NULL;
2855 return
2856 QI(IPersist)
2857 QI(ISubStream)
2858 QI(ISubPicProvider)
2859 QI(ISubPicProviderEx)
2860 __super::NonDelegatingQueryInterface(riid, ppv);
2863 // ISubPicProvider
2865 STDMETHODIMP_(POSITION) CRenderedTextSubtitle::GetStartPosition(REFERENCE_TIME rt, double fps)
2867 //DbgLog((LOG_TRACE, 3, "rt:%lu", (ULONG)rt/10000));
2868 m_fps = fps;//fix me: check is fps changed and do some re-init thing
2869 int iSegment;
2870 int subIndex = 1;//If a segment has animate effect then it corresponds to several subpics.
2871 //subIndex, 1 based, indicates which subpic the result corresponds to.
2872 rt /= 10000i64;
2873 const STSSegment *stss = SearchSubs((int)rt, fps, &iSegment, NULL);
2874 if(stss==NULL)
2875 return NULL;
2876 else if(stss->animated)
2878 int start = TranslateSegmentStart(iSegment, fps);
2879 if(rt > start)
2880 subIndex = (rt-start)/RTS_ANIMATE_SUBPIC_DUR + 1;
2882 //DbgLog((LOG_TRACE, 3, "animated:%d seg:%d idx:%d DUR:%d rt:%lu", stss->animated, iSegment, subIndex, RTS_ANIMATE_SUBPIC_DUR, (ULONG)rt/10000));
2883 return (POSITION)(subIndex | (iSegment<<RTS_POS_SEGMENT_INDEX_BITS));
2884 //if(iSegment < 0) iSegment = 0;
2885 //return(GetNext((POSITION)iSegment));
2888 STDMETHODIMP_(POSITION) CRenderedTextSubtitle::GetNext(POSITION pos)
2890 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2891 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2892 const STSSegment *stss = GetSegment(iSegment);
2893 ASSERT(stss!=NULL && stss->subs.GetCount()>0);
2894 //DbgLog((LOG_TRACE, 3, "stss:%x count:%d", stss, stss->subs.GetCount()));
2895 if(!stss->animated)
2897 iSegment++;
2898 subIndex = 1;
2900 else
2902 int start, end;
2903 TranslateSegmentStartEnd(iSegment, m_fps, start, end);
2904 if(start+RTS_ANIMATE_SUBPIC_DUR*subIndex < end)
2905 subIndex++;
2906 else
2908 iSegment++;
2909 subIndex = 1;
2912 if(GetSegment(iSegment) != NULL)
2914 ASSERT(GetSegment(iSegment)->subs.GetCount()>0);
2915 return (POSITION)(subIndex | (iSegment<<RTS_POS_SEGMENT_INDEX_BITS));
2917 else
2918 return NULL;
2921 //@return: <0 if segment not found
2922 STDMETHODIMP_(REFERENCE_TIME) CRenderedTextSubtitle::GetStart(POSITION pos, double fps)
2924 //return(10000i64 * TranslateSegmentStart((int)pos-1, fps));
2925 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2926 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2927 int start = TranslateSegmentStart(iSegment, fps);
2928 const STSSegment *stss = GetSegment(iSegment);
2929 if(stss!=NULL)
2931 return (start + (subIndex-1)*RTS_ANIMATE_SUBPIC_DUR)*10000i64;
2933 else
2935 return -1;
2939 //@return: <0 if segment not found
2940 STDMETHODIMP_(REFERENCE_TIME) CRenderedTextSubtitle::GetStop(POSITION pos, double fps)
2942 // return(10000i64 * TranslateSegmentEnd((int)pos-1, fps));
2943 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2944 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2945 int start, end, ret;
2946 TranslateSegmentStartEnd(iSegment, fps, start, end);
2947 const STSSegment *stss = GetSegment(iSegment);
2948 if(stss!=NULL)
2950 if(!stss->animated)
2951 ret = end;
2952 else
2954 ret = start+subIndex*RTS_ANIMATE_SUBPIC_DUR;
2955 if(ret > end)
2956 ret = end;
2958 return ret*10000i64;
2960 else
2961 return -1;
2964 //@start, @stop: -1 if segment not found; @stop may < @start if subIndex exceed uppper bound
2965 STDMETHODIMP_(VOID) CRenderedTextSubtitle::GetStartStop(POSITION pos, double fps, /*out*/REFERENCE_TIME &start, /*out*/REFERENCE_TIME &stop)
2967 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2968 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2969 int tempStart, tempEnd;
2970 TranslateSegmentStartEnd(iSegment, fps, tempStart, tempEnd);
2971 start = tempStart;
2972 stop = tempEnd;
2973 const STSSegment *stss = GetSegment(iSegment);
2974 if(stss!=NULL)
2976 if(stss->animated)
2978 start += (subIndex-1)*RTS_ANIMATE_SUBPIC_DUR;
2979 if(start+RTS_ANIMATE_SUBPIC_DUR < stop)
2980 stop = start+RTS_ANIMATE_SUBPIC_DUR;
2982 //DbgLog((LOG_TRACE, 3, "animated:%d seg:%d idx:%d start:%d stop:%lu", stss->animated, iSegment, subIndex, (ULONG)start, (ULONG)stop));
2983 start *= 10000i64;
2984 stop *= 10000i64;
2986 else
2988 start = -1;
2989 stop = -1;
2993 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsAnimated(POSITION pos)
2995 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2996 if(iSegment>=0 && iSegment<m_segments.GetCount())
2997 return m_segments[iSegment].animated;
2998 else
2999 return false;
3000 //return(true);
3003 struct LSub {int idx, layer, readorder;};
3005 static int lscomp(const void* ls1, const void* ls2)
3007 int ret = ((LSub*)ls1)->layer - ((LSub*)ls2)->layer;
3008 if(!ret) ret = ((LSub*)ls1)->readorder - ((LSub*)ls2)->readorder;
3009 return(ret);
3012 STDMETHODIMP CRenderedTextSubtitle::RenderEx(SubPicDesc& spd, REFERENCE_TIME rt, double fps, CAtlList<CRect>& rectList)
3014 CRect bbox2(0,0,0,0);
3015 if(m_size != CSize(spd.w*8, spd.h*8) || m_vidrect != CRect(spd.vidrect.left*8, spd.vidrect.top*8, spd.vidrect.right*8, spd.vidrect.bottom*8))
3016 Init(CSize(spd.w, spd.h), spd.vidrect);
3017 int t = (int)(rt / 10000);
3018 int segment;
3019 //const
3020 STSSegment* stss = SearchSubs2(t, fps, &segment);
3021 if(!stss) return S_FALSE;
3022 // clear any cached subs not in the range of +/-30secs measured from the segment's bounds
3024 POSITION pos = m_subtitleCache.GetStartPosition();
3025 while(pos)
3027 int key;
3028 CSubtitle* value;
3029 m_subtitleCache.GetNextAssoc(pos, key, value);
3030 STSEntry& stse = m_entries.GetAt(key);
3031 if(stse.end <= (t-30000) || stse.start > (t+30000))
3033 delete value;
3034 m_subtitleCache.RemoveKey(key);
3035 pos = m_subtitleCache.GetStartPosition();
3039 m_sla.AdvanceToSegment(segment, stss->subs);
3040 CAtlArray<LSub> subs;
3041 for(int i = 0, j = stss->subs.GetCount(); i < j; i++)
3043 LSub ls;
3044 ls.idx = stss->subs[i];
3045 ls.layer = m_entries.GetAt(stss->subs[i]).layer;
3046 ls.readorder = m_entries.GetAt(stss->subs[i]).readorder;
3047 subs.Add(ls);
3049 qsort(subs.GetData(), subs.GetCount(), sizeof(LSub), lscomp);
3051 CompositeDrawItemList drawItemList;
3052 for(int i = 0, j = subs.GetCount(); i < j; i++)
3054 int entry = subs[i].idx;
3055 STSEntry stse = m_entries.GetAt(entry);
3057 int start = TranslateStart(entry, fps);
3058 m_time = t - start;
3059 m_delay = TranslateEnd(entry, fps) - start;
3061 CSubtitle* s = GetSubtitle(entry);
3062 if(!s) continue;
3063 stss->animated |= s->m_fAnimated2;
3064 CRect clipRect = s->m_clip;
3065 CRect r = s->m_rect;
3066 CSize spaceNeeded = r.Size();
3067 // apply the effects
3068 bool fPosOverride = false, fOrgOverride = false;
3069 int alpha = 0x00;
3070 CPoint org2;
3071 for(int k = 0; k < EF_NUMBEROFEFFECTS; k++)
3073 if(!s->m_effects[k]) continue;
3074 switch(k)
3076 case EF_MOVE: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3], t1=t[0], t2=t[1])}
3078 CPoint p;
3079 CPoint p1(s->m_effects[k]->param[0], s->m_effects[k]->param[1]);
3080 CPoint p2(s->m_effects[k]->param[2], s->m_effects[k]->param[3]);
3081 int t1 = s->m_effects[k]->t[0];
3082 int t2 = s->m_effects[k]->t[1];
3083 if(t2 < t1) {int t = t1; t1 = t2; t2 = t;}
3084 if(t1 <= 0 && t2 <= 0) {t1 = 0; t2 = m_delay;}
3085 if(m_time <= t1) p = p1;
3086 else if (p1 == p2) p = p1;
3087 else if(t1 < m_time && m_time < t2)
3089 double t = 1.0*(m_time-t1)/(t2-t1);
3090 p.x = (int)((1-t)*p1.x + t*p2.x);
3091 p.y = (int)((1-t)*p1.y + t*p2.y);
3093 else p = p2;
3094 r = CRect(
3095 CPoint((s->m_scrAlignment%3) == 1 ? p.x : (s->m_scrAlignment%3) == 0 ? p.x - spaceNeeded.cx : p.x - (spaceNeeded.cx+1)/2,
3096 s->m_scrAlignment <= 3 ? p.y - spaceNeeded.cy : s->m_scrAlignment <= 6 ? p.y - (spaceNeeded.cy+1)/2 : p.y),
3097 spaceNeeded);
3098 if(s->m_relativeTo == 1)
3099 r.OffsetRect(m_vidrect.TopLeft());
3100 fPosOverride = true;
3102 break;
3103 case EF_ORG: // {\org(x=param[0], y=param[1])}
3105 org2 = CPoint(s->m_effects[k]->param[0], s->m_effects[k]->param[1]);
3106 fOrgOverride = true;
3108 break;
3109 case EF_FADE: // {\fade(a1=param[0], a2=param[1], a3=param[2], t1=t[0], t2=t[1], t3=t[2], t4=t[3]) or {\fad(t1=t[1], t2=t[2])
3111 int t1 = s->m_effects[k]->t[0];
3112 int t2 = s->m_effects[k]->t[1];
3113 int t3 = s->m_effects[k]->t[2];
3114 int t4 = s->m_effects[k]->t[3];
3115 if(t1 == -1 && t4 == -1) {t1 = 0; t3 = m_delay-t3; t4 = m_delay;}
3116 if(m_time < t1) alpha = s->m_effects[k]->param[0];
3117 else if(m_time >= t1 && m_time < t2)
3119 double t = 1.0 * (m_time - t1) / (t2 - t1);
3120 alpha = (int)(s->m_effects[k]->param[0]*(1-t) + s->m_effects[k]->param[1]*t);
3122 else if(m_time >= t2 && m_time < t3) alpha = s->m_effects[k]->param[1];
3123 else if(m_time >= t3 && m_time < t4)
3125 double t = 1.0 * (m_time - t3) / (t4 - t3);
3126 alpha = (int)(s->m_effects[k]->param[1]*(1-t) + s->m_effects[k]->param[2]*t);
3128 else if(m_time >= t4) alpha = s->m_effects[k]->param[2];
3130 break;
3131 case EF_BANNER: // Banner;delay=param[0][;leftoright=param[1];fadeawaywidth=param[2]]
3133 int left = s->m_relativeTo == 1 ? m_vidrect.left : 0,
3134 right = s->m_relativeTo == 1 ? m_vidrect.right : m_size.cx;
3135 r.left = !!s->m_effects[k]->param[1]
3136 ? (left/*marginRect.left*/ - spaceNeeded.cx) + (int)(m_time*8.0/s->m_effects[k]->param[0])
3137 : (right /*- marginRect.right*/) - (int)(m_time*8.0/s->m_effects[k]->param[0]);
3138 r.right = r.left + spaceNeeded.cx;
3139 clipRect &= CRect(left>>3, clipRect.top, right>>3, clipRect.bottom);
3140 fPosOverride = true;
3142 break;
3143 case EF_SCROLL: // Scroll up/down(toptobottom=param[3]);top=param[0];bottom=param[1];delay=param[2][;fadeawayheight=param[4]]
3145 r.top = !!s->m_effects[k]->param[3]
3146 ? s->m_effects[k]->param[0] + (int)(m_time*8.0/s->m_effects[k]->param[2]) - spaceNeeded.cy
3147 : s->m_effects[k]->param[1] - (int)(m_time*8.0/s->m_effects[k]->param[2]);
3148 r.bottom = r.top + spaceNeeded.cy;
3149 CRect cr(0, (s->m_effects[k]->param[0] + 4) >> 3, spd.w, (s->m_effects[k]->param[1] + 4) >> 3);
3150 if(s->m_relativeTo == 1)
3151 r.top += m_vidrect.top,
3152 r.bottom += m_vidrect.top,
3153 cr.top += m_vidrect.top>>3,
3154 cr.bottom += m_vidrect.top>>3;
3155 clipRect &= cr;
3156 fPosOverride = true;
3158 break;
3159 default:
3160 break;
3163 if(!fPosOverride && !fOrgOverride && !s->m_fAnimated)
3164 r = m_sla.AllocRect(s, segment, entry, stse.layer, m_collisions);
3165 CPoint org;
3166 org.x = (s->m_scrAlignment%3) == 1 ? r.left : (s->m_scrAlignment%3) == 2 ? r.CenterPoint().x : r.right;
3167 org.y = s->m_scrAlignment <= 3 ? r.bottom : s->m_scrAlignment <= 6 ? r.CenterPoint().y : r.top;
3168 if(!fOrgOverride) org2 = org;
3169 SharedArrayByte pAlphaMask;
3170 if( s->m_pClipper )
3171 pAlphaMask = s->m_pClipper->m_pAlphaMask;
3172 CPoint p, p2(0, r.top);
3173 POSITION pos;
3174 p = p2;
3175 // Rectangles for inverse clip
3176 CRect iclipRect[4];
3177 iclipRect[0] = CRect(0, 0, spd.w, clipRect.top);
3178 iclipRect[1] = CRect(0, clipRect.top, clipRect.left, clipRect.bottom);
3179 iclipRect[2] = CRect(clipRect.right, clipRect.top, spd.w, clipRect.bottom);
3180 iclipRect[3] = CRect(0, clipRect.bottom, spd.w, spd.h);
3181 int dbgTest = 0;
3182 bbox2 = CRect(0,0,0,0);
3183 pos = s->GetHeadLinePosition();
3184 while(pos)
3186 CLine* l = s->GetNextLine(pos);
3187 p.x = (s->m_scrAlignment%3) == 1 ? org.x
3188 : (s->m_scrAlignment%3) == 0 ? org.x - l->m_width
3189 : org.x - (l->m_width/2);
3191 CompositeDrawItemList tmpDrawItemList;
3192 if (s->m_clipInverse)
3194 for (int i=0;i<l->GetWordCount();i++)
3196 tmpDrawItemList.AddTail();
3197 tmpDrawItemList.AddTail();
3198 tmpDrawItemList.AddTail();
3199 tmpDrawItemList.AddTail();
3201 bbox2 |= l->PaintShadow(&tmpDrawItemList, spd, iclipRect[0], pAlphaMask, p, org2, m_time, alpha);
3202 bbox2 |= l->PaintShadow(&tmpDrawItemList, spd, iclipRect[1], pAlphaMask, p, org2, m_time, alpha);
3203 bbox2 |= l->PaintShadow(&tmpDrawItemList, spd, iclipRect[2], pAlphaMask, p, org2, m_time, alpha);
3204 bbox2 |= l->PaintShadow(&tmpDrawItemList, spd, iclipRect[3], pAlphaMask, p, org2, m_time, alpha);
3206 bbox2 |= l->PaintOutline(&tmpDrawItemList, spd, iclipRect[0], pAlphaMask, p, org2, m_time, alpha);
3207 bbox2 |= l->PaintOutline(&tmpDrawItemList, spd, iclipRect[1], pAlphaMask, p, org2, m_time, alpha);
3208 bbox2 |= l->PaintOutline(&tmpDrawItemList, spd, iclipRect[2], pAlphaMask, p, org2, m_time, alpha);
3209 bbox2 |= l->PaintOutline(&tmpDrawItemList, spd, iclipRect[3], pAlphaMask, p, org2, m_time, alpha);
3211 bbox2 |= l->PaintBody(&tmpDrawItemList, spd, iclipRect[0], pAlphaMask, p, org2, m_time, alpha);
3212 bbox2 |= l->PaintBody(&tmpDrawItemList, spd, iclipRect[1], pAlphaMask, p, org2, m_time, alpha);
3213 bbox2 |= l->PaintBody(&tmpDrawItemList, spd, iclipRect[2], pAlphaMask, p, org2, m_time, alpha);
3214 bbox2 |= l->PaintBody(&tmpDrawItemList, spd, iclipRect[3], pAlphaMask, p, org2, m_time, alpha);
3216 else
3218 for (int i=0;i<l->GetWordCount();i++)
3220 tmpDrawItemList.AddTail();
3222 bbox2 |= l->PaintShadow(&tmpDrawItemList, spd, clipRect, pAlphaMask, p, org2, m_time, alpha);
3224 bbox2 |= l->PaintOutline(&tmpDrawItemList, spd, clipRect, pAlphaMask, p, org2, m_time, alpha);
3226 bbox2 |= l->PaintBody(&tmpDrawItemList, spd, clipRect, pAlphaMask, p, org2, m_time, alpha);
3229 drawItemList.AddTailList(&tmpDrawItemList);
3230 p.y += l->m_ascent + l->m_descent;
3232 rectList.AddTail(bbox2);
3235 Draw(spd, drawItemList);
3236 return (subs.GetCount() && !rectList.IsEmpty()) ? S_OK : S_FALSE;
3240 STDMETHODIMP CRenderedTextSubtitle::Render(SubPicDesc& spd, REFERENCE_TIME rt, double fps, RECT& bbox)
3242 CAtlList<CRect> rectList;
3243 HRESULT result = RenderEx(spd, rt, fps, rectList);
3244 POSITION pos = rectList.GetHeadPosition();
3245 CRect bbox2(0,0,0,0);
3246 while(pos!=NULL)
3248 bbox2 |= rectList.GetNext(pos);
3250 bbox = bbox2;
3251 return result;
3254 // IPersist
3256 STDMETHODIMP CRenderedTextSubtitle::GetClassID(CLSID* pClassID)
3258 return pClassID ? *pClassID = __uuidof(this), S_OK : E_POINTER;
3261 // ISubStream
3263 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStreamCount()
3265 return(1);
3268 STDMETHODIMP CRenderedTextSubtitle::GetStreamInfo(int iStream, WCHAR** ppName, LCID* pLCID)
3270 if(iStream != 0) return E_INVALIDARG;
3271 if(ppName)
3273 if(!(*ppName = (WCHAR*)CoTaskMemAlloc((m_name.GetLength()+1)*sizeof(WCHAR))))
3274 return E_OUTOFMEMORY;
3275 wcscpy(*ppName, CStringW(m_name));
3277 if(pLCID)
3279 *pLCID = 0; // TODO
3281 return S_OK;
3284 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStream()
3286 return(0);
3289 STDMETHODIMP CRenderedTextSubtitle::SetStream(int iStream)
3291 return iStream == 0 ? S_OK : E_FAIL;
3294 STDMETHODIMP CRenderedTextSubtitle::Reload()
3296 CFileStatus s;
3297 if(!CFile::GetStatus(m_path, s)) return E_FAIL;
3298 return !m_path.IsEmpty() && Open(m_path, DEFAULT_CHARSET) ? S_OK : E_FAIL;
3301 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsColorTypeSupported( int type )
3303 return type==MSP_AY11 ||
3304 type==MSP_AYUV ||
3305 type==MSP_AUYV ||
3306 type==MSP_RGBA;
3309 void CRenderedTextSubtitle::Draw( SubPicDesc& spd, CompositeDrawItemList& drawItemList )
3311 POSITION pos = drawItemList.GetHeadPosition();
3312 while(pos)
3314 CompositeDrawItem& draw_item = drawItemList.GetNext(pos);
3315 if(draw_item.shadow)
3316 Rasterizer::Draw( spd, *draw_item.shadow );
3318 pos = drawItemList.GetHeadPosition();
3319 while(pos)
3321 CompositeDrawItem& draw_item = drawItemList.GetNext(pos);
3322 if(draw_item.outline)
3323 Rasterizer::Draw( spd, *draw_item.outline );
3325 pos = drawItemList.GetHeadPosition();
3326 while(pos)
3328 CompositeDrawItem& draw_item = drawItemList.GetNext(pos);
3329 if(draw_item.body)
3330 Rasterizer::Draw( spd, *draw_item.body );