Add parsed data cache.
[xy_vsfilter.git] / src / subtitles / RTS.cpp
blob1fb581ab419f0343425a003609191fc1977f51e2
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( AssTagList *assTags, const CStringW& str )
1962 if(!assTags) return(false);
1963 int nTags = 0, nUnrecognizedTags = 0;
1964 for(int i = 0, j; (j = str.Find(L'\\', i)) >= 0; i = j)
1966 POSITION pos = assTags->AddTail();
1967 AssTag& assTag = assTags->GetAt(pos);
1968 assTag.cmdType = CMD_COUNT;
1970 j++;
1971 CStringW::PCXSTR str_start = str.GetString() + j;
1972 CStringW::PCXSTR pc = str_start;
1973 while( iswspace(*pc) )
1975 pc++;
1977 j += pc-str_start;
1978 str_start = pc;
1979 while( *pc && *pc != L'(' && *pc != L'\\' )
1981 pc++;
1983 j += pc-str_start;
1984 if( pc-str_start>0 )
1986 while( iswspace(*--pc) );
1987 pc++;
1990 const CStringW cmd(str_start, pc-str_start);
1991 if(cmd.IsEmpty()) continue;
1993 CAtlArray<CStringW>& params = assTag.strParams;
1994 if(str[j] == L'(')
1996 j++;
1997 CStringW::PCXSTR str_start = str.GetString() + j;
1998 CStringW::PCXSTR pc = str_start;
1999 while( iswspace(*pc) )
2001 pc++;
2003 j += pc-str_start;
2004 str_start = pc;
2005 while( *pc && *pc != L')' )
2007 pc++;
2009 j += pc-str_start;
2010 if( pc-str_start>0 )
2012 while( iswspace(*--pc) );
2013 pc++;
2016 CStringW::PCXSTR param_start = str_start;
2017 CStringW::PCXSTR param_end = pc;
2018 while( param_start<param_end )
2020 param_start = SkipWhiteSpaceLeft(param_start, param_end);
2022 CStringW::PCXSTR newstart = FindChar(param_start, param_end, L',');
2023 CStringW::PCXSTR newend = FindChar(param_start, param_end, L'\\');
2024 if(newstart > param_start && newstart < newend)
2026 newstart = FastSkipWhiteSpaceRight(param_start, newstart);
2027 CStringW s(param_start, newstart - param_start);
2029 if(!s.IsEmpty()) params.Add(s);
2030 param_start = newstart + 1;
2032 else if(param_start<param_end)
2034 CStringW s(param_start, param_end - param_start);
2036 params.Add(s);
2037 param_start = param_end;
2042 AssCmdType cmd_type = CMD_COUNT;
2043 int cmd_length = min(MAX_CMD_LENGTH, cmd.GetLength());
2044 for( ;cmd_length>=MIN_CMD_LENGTH;cmd_length-- )
2046 if( m_cmdMap.Lookup(cmd.Left(cmd_length), cmd_type) )
2047 break;
2049 if(cmd_length<MIN_CMD_LENGTH)
2050 cmd_type = CMD_COUNT;
2051 switch( cmd_type )
2053 case CMD_fax:
2054 case CMD_fay:
2055 case CMD_fe:
2056 case CMD_fn:
2057 case CMD_frx:
2058 case CMD_fry:
2059 case CMD_frz:
2060 case CMD_fr:
2061 case CMD_fscx:
2062 case CMD_fscy:
2063 case CMD_fsc:
2064 case CMD_fsp:
2065 case CMD_fs:
2066 case CMD_i:
2067 case CMD_kt:
2068 case CMD_kf:
2069 case CMD_K:
2070 case CMD_ko:
2071 case CMD_k:
2072 case CMD_pbo:
2073 case CMD_p:
2074 case CMD_q:
2075 case CMD_r:
2076 case CMD_shad:
2077 case CMD_s:
2078 case CMD_an:
2079 case CMD_a:
2080 case CMD_blur:
2081 case CMD_bord:
2082 case CMD_be:
2083 case CMD_b:
2084 case CMD_u:
2085 case CMD_xbord:
2086 case CMD_xshad:
2087 case CMD_ybord:
2088 case CMD_yshad:
2089 // default:
2090 params.Add(cmd.Mid(cmd_length));
2091 break;
2092 case CMD_c:
2093 case CMD_1c :
2094 case CMD_2c :
2095 case CMD_3c :
2096 case CMD_4c :
2097 case CMD_1a :
2098 case CMD_2a :
2099 case CMD_3a :
2100 case CMD_4a :
2101 case CMD_alpha:
2102 params.Add(cmd.Mid(cmd_length).Trim(L"&H"));
2103 break;
2104 case CMD_clip:
2105 case CMD_iclip:
2106 case CMD_fade:
2107 case CMD_fad:
2108 case CMD_move:
2109 case CMD_org:
2110 case CMD_pos:
2111 break;
2112 case CMD_t:
2113 ParseSSATag(&assTag.embeded, params[0]);
2114 break;
2115 case CMD_COUNT:
2116 nUnrecognizedTags++;
2117 break;
2120 assTag.cmd = cmd;
2121 assTag.cmdType = cmd_type;
2123 nTags++;
2125 return(true);
2128 bool CRenderedTextSubtitle::ParseSSATag( CSubtitle* sub, const AssTagList& assTags, STSStyle& style, const STSStyle& org, bool fAnimate /*= false*/ )
2130 if(!sub) return(false);
2132 POSITION pos = assTags.GetHeadPosition();
2133 while(pos)
2135 const AssTag& assTag = assTags.GetNext(pos);
2136 const CStringW& cmd = assTag.cmd;
2137 AssCmdType cmd_type = assTag.cmdType;
2138 const CAtlArray<CStringW>& params = assTag.strParams;
2140 // TODO: call ParseStyleModifier(cmd, params, ..) and move the rest there
2141 const CStringW& p = params.GetCount() > 0 ? params[0] : CStringW("");
2142 switch ( cmd_type )
2144 case CMD_1c :
2145 case CMD_2c :
2146 case CMD_3c :
2147 case CMD_4c :
2149 int i = cmd[0] - L'1';
2150 DWORD c = wcstol(p, NULL, 16);
2151 style.colors[i] = !p.IsEmpty()
2152 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2153 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2154 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2155 : org.colors[i];
2156 break;
2158 case CMD_1a :
2159 case CMD_2a :
2160 case CMD_3a :
2161 case CMD_4a :
2163 int i = cmd[0] - L'1';
2164 style.alpha[i] = !p.IsEmpty()
2165 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2166 : org.alpha[i];
2167 break;
2169 case CMD_alpha:
2171 for(int i = 0; i < 4; i++)
2173 style.alpha[i] = !p.IsEmpty()
2174 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2175 : org.alpha[i];
2177 break;
2179 case CMD_an:
2181 int n = wcstol(p, NULL, 10);
2182 if(sub->m_scrAlignment < 0)
2183 sub->m_scrAlignment = (n > 0 && n < 10) ? n : org.scrAlignment;
2184 break;
2186 case CMD_a:
2188 int n = wcstol(p, NULL, 10);
2189 if(sub->m_scrAlignment < 0)
2190 sub->m_scrAlignment = (n > 0 && n < 12) ? ((((n-1)&3)+1)+((n&4)?6:0)+((n&8)?3:0)) : org.scrAlignment;
2191 break;
2193 case CMD_blur:
2195 double n = CalcAnimation(wcstod(p, NULL), style.fGaussianBlur, fAnimate);
2196 style.fGaussianBlur = !p.IsEmpty()
2197 ? (n < 0 ? 0 : n)
2198 : org.fGaussianBlur;
2199 break;
2201 case CMD_bord:
2203 double dst = wcstod(p, NULL);
2204 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2205 style.outlineWidthX = !p.IsEmpty()
2206 ? (nx < 0 ? 0 : nx)
2207 : org.outlineWidthX;
2208 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2209 style.outlineWidthY = !p.IsEmpty()
2210 ? (ny < 0 ? 0 : ny)
2211 : org.outlineWidthY;
2212 break;
2214 case CMD_be:
2216 int n = (int)(CalcAnimation(wcstol(p, NULL, 10), style.fBlur, fAnimate)+0.5);
2217 style.fBlur = !p.IsEmpty()
2219 : org.fBlur;
2220 break;
2222 case CMD_b:
2224 int n = wcstol(p, NULL, 10);
2225 style.fontWeight = !p.IsEmpty()
2226 ? (n == 0 ? FW_NORMAL : n == 1 ? FW_BOLD : n >= 100 ? n : org.fontWeight)
2227 : org.fontWeight;
2228 break;
2230 case CMD_clip:
2231 case CMD_iclip:
2233 bool invert = (cmd_type == CMD_iclip);
2234 if(params.GetCount() == 1 && !sub->m_pClipper)
2236 sub->m_pClipper = new CClipper(params[0], CSize(m_size.cx>>3, m_size.cy>>3), sub->m_scalex, sub->m_scaley, invert);
2238 else if(params.GetCount() == 2 && !sub->m_pClipper)
2240 int scale = max(wcstol(p, NULL, 10), 1);
2241 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);
2243 else if(params.GetCount() == 4)
2245 CRect r;
2246 sub->m_clipInverse = invert;
2247 r.SetRect(
2248 wcstol(params[0], NULL, 10),
2249 wcstol(params[1], NULL, 10),
2250 wcstol(params[2], NULL, 10),
2251 wcstol(params[3], NULL, 10));
2252 CPoint o(0, 0);
2253 if(sub->m_relativeTo == 1) // TODO: this should also apply to the other two clippings above
2255 o.x = m_vidrect.left>>3;
2256 o.y = m_vidrect.top>>3;
2258 sub->m_clip.SetRect(
2259 (int)CalcAnimation(sub->m_scalex*r.left + o.x, sub->m_clip.left, fAnimate),
2260 (int)CalcAnimation(sub->m_scaley*r.top + o.y, sub->m_clip.top, fAnimate),
2261 (int)CalcAnimation(sub->m_scalex*r.right + o.x, sub->m_clip.right, fAnimate),
2262 (int)CalcAnimation(sub->m_scaley*r.bottom + o.y, sub->m_clip.bottom, fAnimate));
2264 break;
2266 case CMD_c:
2268 DWORD c = wcstol(p, NULL, 16);
2269 style.colors[0] = !p.IsEmpty()
2270 ? (((int)CalcAnimation(c&0xff, style.colors[0]&0xff, fAnimate))&0xff
2271 |((int)CalcAnimation(c&0xff00, style.colors[0]&0xff00, fAnimate))&0xff00
2272 |((int)CalcAnimation(c&0xff0000, style.colors[0]&0xff0000, fAnimate))&0xff0000)
2273 : org.colors[0];
2274 break;
2276 case CMD_fade:
2277 case CMD_fad:
2279 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])
2281 if(Effect* e = new Effect)
2283 for(int i = 0; i < 3; i++)
2284 e->param[i] = wcstol(params[i], NULL, 10);
2285 for(int i = 0; i < 4; i++)
2286 e->t[i] = wcstol(params[3+i], NULL, 10);
2287 sub->m_effects[EF_FADE] = e;
2290 else if(params.GetCount() == 2 && !sub->m_effects[EF_FADE]) // {\fad(t1=t[1], t2=t[2])
2292 if(Effect* e = new Effect)
2294 e->param[0] = e->param[2] = 0xff;
2295 e->param[1] = 0x00;
2296 for(int i = 1; i < 3; i++)
2297 e->t[i] = wcstol(params[i-1], NULL, 10);
2298 e->t[0] = e->t[3] = -1; // will be substituted with "start" and "end"
2299 sub->m_effects[EF_FADE] = e;
2302 break;
2304 case CMD_fax:
2306 style.fontShiftX = !p.IsEmpty()
2307 ? CalcAnimation(wcstod(p, NULL), style.fontShiftX, fAnimate)
2308 : org.fontShiftX;
2309 break;
2311 case CMD_fay:
2313 style.fontShiftY = !p.IsEmpty()
2314 ? CalcAnimation(wcstod(p, NULL), style.fontShiftY, fAnimate)
2315 : org.fontShiftY;
2316 break;
2318 case CMD_fe:
2320 int n = wcstol(p, NULL, 10);
2321 style.charSet = !p.IsEmpty()
2323 : org.charSet;
2324 break;
2326 case CMD_fn:
2328 if(!p.IsEmpty() && p != L'0')
2329 style.fontName = CString(p).Trim();
2330 else
2331 style.fontName = org.fontName;
2332 break;
2334 case CMD_frx:
2336 style.fontAngleX = !p.IsEmpty()
2337 ? CalcAnimation(wcstod(p, NULL), style.fontAngleX, fAnimate)
2338 : org.fontAngleX;
2339 break;
2341 case CMD_fry:
2343 style.fontAngleY = !p.IsEmpty()
2344 ? CalcAnimation(wcstod(p, NULL), style.fontAngleY, fAnimate)
2345 : org.fontAngleY;
2346 break;
2348 case CMD_frz:
2349 case CMD_fr:
2351 style.fontAngleZ = !p.IsEmpty()
2352 ? CalcAnimation(wcstod(p, NULL), style.fontAngleZ, fAnimate)
2353 : org.fontAngleZ;
2354 break;
2356 case CMD_fscx:
2358 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontScaleX, fAnimate);
2359 style.fontScaleX = !p.IsEmpty()
2360 ? ((n < 0) ? 0 : n)
2361 : org.fontScaleX;
2362 break;
2364 case CMD_fscy:
2366 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontScaleY, fAnimate);
2367 style.fontScaleY = !p.IsEmpty()
2368 ? ((n < 0) ? 0 : n)
2369 : org.fontScaleY;
2370 break;
2372 case CMD_fsc:
2374 style.fontScaleX = org.fontScaleX;
2375 style.fontScaleY = org.fontScaleY;
2376 break;
2378 case CMD_fsp:
2380 style.fontSpacing = !p.IsEmpty()
2381 ? CalcAnimation(wcstod(p, NULL), style.fontSpacing, fAnimate)
2382 : org.fontSpacing;
2383 break;
2385 case CMD_fs:
2387 if(!p.IsEmpty())
2389 if(p[0] == L'-' || p[0] == L'+')
2391 double n = CalcAnimation(style.fontSize + style.fontSize*wcstol(p, NULL, 10)/10, style.fontSize, fAnimate);
2392 style.fontSize = (n > 0) ? n : org.fontSize;
2394 else
2396 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontSize, fAnimate);
2397 style.fontSize = (n > 0) ? n : org.fontSize;
2400 else
2402 style.fontSize = org.fontSize;
2404 break;
2406 case CMD_i:
2408 int n = wcstol(p, NULL, 10);
2409 style.fItalic = !p.IsEmpty()
2410 ? (n == 0 ? false : n == 1 ? true : org.fItalic)
2411 : org.fItalic;
2412 break;
2414 case CMD_kt:
2416 m_kstart = !p.IsEmpty()
2417 ? wcstol(p, NULL, 10)*10
2418 : 0;
2419 m_kend = m_kstart;
2420 break;
2421 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2423 case CMD_kf:
2424 case CMD_K:
2426 m_ktype = 1;
2427 m_kstart = m_kend;
2428 m_kend += !p.IsEmpty()
2429 ? wcstol(p, NULL, 10)*10
2430 : 1000;
2431 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2432 break;
2434 case CMD_ko:
2436 m_ktype = 2;
2437 m_kstart = m_kend;
2438 m_kend += !p.IsEmpty()
2439 ? wcstol(p, NULL, 10)*10
2440 : 1000;
2441 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2442 break;
2444 case CMD_k:
2446 m_ktype = 0;
2447 m_kstart = m_kend;
2448 m_kend += !p.IsEmpty()
2449 ? wcstol(p, NULL, 10)*10
2450 : 1000;
2451 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2452 break;
2454 case CMD_move: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3][, t1=t[0], t2=t[1]])}
2456 if((params.GetCount() == 4 || params.GetCount() == 6) && !sub->m_effects[EF_MOVE])
2458 if(Effect* e = new Effect)
2460 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2461 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2462 e->param[2] = (int)(sub->m_scalex*wcstod(params[2], NULL)*8);
2463 e->param[3] = (int)(sub->m_scaley*wcstod(params[3], NULL)*8);
2464 e->t[0] = e->t[1] = -1;
2465 if(params.GetCount() == 6)
2467 for(int i = 0; i < 2; i++)
2468 e->t[i] = wcstol(params[4+i], NULL, 10);
2470 sub->m_effects[EF_MOVE] = e;
2473 break;
2475 case CMD_org: // {\org(x=param[0], y=param[1])}
2477 if(params.GetCount() == 2 && !sub->m_effects[EF_ORG])
2479 if(Effect* e = new Effect)
2481 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2482 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2483 sub->m_effects[EF_ORG] = e;
2486 break;
2488 case CMD_pbo:
2490 m_polygonBaselineOffset = wcstol(p, NULL, 10);
2491 break;
2493 case CMD_pos:
2495 if(params.GetCount() == 2 && !sub->m_effects[EF_MOVE])
2497 if(Effect* e = new Effect)
2499 e->param[0] = e->param[2] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2500 e->param[1] = e->param[3] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2501 e->t[0] = e->t[1] = 0;
2502 sub->m_effects[EF_MOVE] = e;
2505 break;
2507 case CMD_p:
2509 int n = wcstol(p, NULL, 10);
2510 m_nPolygon = (n <= 0 ? 0 : n);
2511 break;
2513 case CMD_q:
2515 int n = wcstol(p, NULL, 10);
2516 sub->m_wrapStyle = !p.IsEmpty() && (0 <= n && n <= 3)
2518 : m_defaultWrapStyle;
2519 break;
2521 case CMD_r:
2523 STSStyle* val;
2524 style = (!p.IsEmpty() && m_styles.Lookup(WToT(p), val) && val) ? *val : org;
2525 break;
2527 case CMD_shad:
2529 double dst = wcstod(p, NULL);
2530 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2531 style.shadowDepthX = !p.IsEmpty()
2532 ? (nx < 0 ? 0 : nx)
2533 : org.shadowDepthX;
2534 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2535 style.shadowDepthY = !p.IsEmpty()
2536 ? (ny < 0 ? 0 : ny)
2537 : org.shadowDepthY;
2538 break;
2540 case CMD_s:
2542 int n = wcstol(p, NULL, 10);
2543 style.fStrikeOut = !p.IsEmpty()
2544 ? (n == 0 ? false : n == 1 ? true : org.fStrikeOut)
2545 : org.fStrikeOut;
2546 break;
2548 case CMD_t: // \t([<t1>,<t2>,][<accel>,]<style modifiers>)
2550 CStringW param;
2551 m_animStart = m_animEnd = 0;
2552 m_animAccel = 1;
2553 if(params.GetCount() == 1)
2555 param = params[0];
2557 else if(params.GetCount() == 2)
2559 m_animAccel = wcstod(params[0], NULL);
2560 param = params[1];
2562 else if(params.GetCount() == 3)
2564 m_animStart = (int)wcstod(params[0], NULL);
2565 m_animEnd = (int)wcstod(params[1], NULL);
2566 param = params[2];
2568 else if(params.GetCount() == 4)
2570 m_animStart = wcstol(params[0], NULL, 10);
2571 m_animEnd = wcstol(params[1], NULL, 10);
2572 m_animAccel = wcstod(params[2], NULL);
2573 param = params[3];
2575 ParseSSATag(sub, assTag.embeded, style, org, true);
2576 sub->m_fAnimated = true;
2577 break;
2579 case CMD_u:
2581 int n = wcstol(p, NULL, 10);
2582 style.fUnderline = !p.IsEmpty()
2583 ? (n == 0 ? false : n == 1 ? true : org.fUnderline)
2584 : org.fUnderline;
2585 break;
2587 case CMD_xbord:
2589 double dst = wcstod(p, NULL);
2590 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2591 style.outlineWidthX = !p.IsEmpty()
2592 ? (nx < 0 ? 0 : nx)
2593 : org.outlineWidthX;
2594 break;
2596 case CMD_xshad:
2598 double dst = wcstod(p, NULL);
2599 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2600 style.shadowDepthX = !p.IsEmpty()
2601 ? nx
2602 : org.shadowDepthX;
2603 break;
2605 case CMD_ybord:
2607 double dst = wcstod(p, NULL);
2608 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2609 style.outlineWidthY = !p.IsEmpty()
2610 ? (ny < 0 ? 0 : ny)
2611 : org.outlineWidthY;
2612 break;
2614 case CMD_yshad:
2616 double dst = wcstod(p, NULL);
2617 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2618 style.shadowDepthY = !p.IsEmpty()
2619 ? ny
2620 : org.shadowDepthY;
2621 break;
2623 default:
2624 break;
2627 return(true);
2630 bool CRenderedTextSubtitle::ParseSSATag(CSubtitle* sub, const CStringW& str, STSStyle& style, const STSStyle& org, bool fAnimate)
2632 if(!sub) return(false);
2634 SharedPtrConstAssTagList assTags;
2635 AssTagListMruCache *ass_tag_cache = CacheManager::GetAssTagListMruCache();
2636 AssTagListMruCache::hashed_cache_const_iterator iter = ass_tag_cache->hash_find(str);
2637 if (iter==ass_tag_cache->hash_end())
2639 AssTagList *tmp = new AssTagList();
2640 ParseSSATag(tmp, str);
2641 assTags.reset(tmp);
2642 AssTagListMruItem item;
2643 item.script = str; item.tag_list = assTags;
2644 ass_tag_cache->update_cache( item );
2646 else
2648 assTags = iter->tag_list;
2649 ass_tag_cache->update_cache( *iter );
2651 return ParseSSATag(sub, *assTags, style, org, fAnimate);
2654 bool CRenderedTextSubtitle::ParseHtmlTag(CSubtitle* sub, CStringW str, STSStyle& style, STSStyle& org)
2656 if(str.Find(L"!--") == 0)
2657 return(true);
2658 bool fClosing = str[0] == L'/';
2659 str.Trim(L" /");
2660 int i = str.Find(L' ');
2661 if(i < 0) i = str.GetLength();
2662 CStringW tag = str.Left(i).MakeLower();
2663 str = str.Mid(i).Trim();
2664 CAtlArray<CStringW> attribs, params;
2665 while((i = str.Find(L'=')) > 0)
2667 attribs.Add(str.Left(i).Trim().MakeLower());
2668 str = str.Mid(i+1);
2669 for(i = 0; _istspace(str[i]); i++);
2670 str = str.Mid(i);
2671 if(str[0] == L'\"') {str = str.Mid(1); i = str.Find(L'\"');}
2672 else i = str.Find(L' ');
2673 if(i < 0) i = str.GetLength();
2674 params.Add(str.Left(i).Trim().MakeLower());
2675 str = str.Mid(i+1);
2677 if(tag == L"text")
2679 else if(tag == L"b" || tag == L"strong")
2680 style.fontWeight = !fClosing ? FW_BOLD : org.fontWeight;
2681 else if(tag == L"i" || tag == L"em")
2682 style.fItalic = !fClosing ? true : org.fItalic;
2683 else if(tag == L"u")
2684 style.fUnderline = !fClosing ? true : org.fUnderline;
2685 else if(tag == L"s" || tag == L"strike" || tag == L"del")
2686 style.fStrikeOut = !fClosing ? true : org.fStrikeOut;
2687 else if(tag == L"font")
2689 if(!fClosing)
2691 for(size_t i = 0; i < attribs.GetCount(); i++)
2693 if(params[i].IsEmpty()) continue;
2694 int nColor = -1;
2695 if(attribs[i] == L"face")
2697 style.fontName = params[i];
2699 else if(attribs[i] == L"size")
2701 if(params[i][0] == L'+')
2702 style.fontSize += wcstol(params[i], NULL, 10);
2703 else if(params[i][0] == L'-')
2704 style.fontSize -= wcstol(params[i], NULL, 10);
2705 else
2706 style.fontSize = wcstol(params[i], NULL, 10);
2708 else if(attribs[i] == L"color")
2710 nColor = 0;
2712 else if(attribs[i] == L"outline-color")
2714 nColor = 2;
2716 else if(attribs[i] == L"outline-level")
2718 style.outlineWidthX = style.outlineWidthY = wcstol(params[i], NULL, 10);
2720 else if(attribs[i] == L"shadow-color")
2722 nColor = 3;
2724 else if(attribs[i] == L"shadow-level")
2726 style.shadowDepthX = style.shadowDepthY = wcstol(params[i], NULL, 10);
2728 if(nColor >= 0 && nColor < 4)
2730 CString key = WToT(params[i]).TrimLeft(L'#');
2731 DWORD val;
2732 if(g_colors.Lookup(key, val))
2733 style.colors[nColor] = val;
2734 else if((style.colors[nColor] = _tcstol(key, NULL, 16)) == 0)
2735 style.colors[nColor] = 0x00ffffff; // default is white
2736 style.colors[nColor] = ((style.colors[nColor]>>16)&0xff)|((style.colors[nColor]&0xff)<<16)|(style.colors[nColor]&0x00ff00);
2740 else
2742 style.fontName = org.fontName;
2743 style.fontSize = org.fontSize;
2744 memcpy(style.colors, org.colors, sizeof(style.colors));
2747 else if(tag == L"k" && attribs.GetCount() == 1 && attribs[0] == L"t")
2749 m_ktype = 1;
2750 m_kstart = m_kend;
2751 m_kend += wcstol(params[0], NULL, 10);
2753 else
2754 return(false);
2755 return(true);
2758 double CRenderedTextSubtitle::CalcAnimation(double dst, double src, bool fAnimate)
2760 int s = m_animStart ? m_animStart : 0;
2761 int e = m_animEnd ? m_animEnd : m_delay;
2762 if(fabs(dst-src) >= 0.0001 && fAnimate)
2764 if(m_time < s) dst = src;
2765 else if(s <= m_time && m_time < e)
2767 double t = pow(1.0 * (m_time - s) / (e - s), m_animAccel);
2768 dst = (1 - t) * src + t * dst;
2770 // else dst = dst;
2772 return(dst);
2775 CSubtitle* CRenderedTextSubtitle::GetSubtitle(int entry)
2777 CSubtitle* sub;
2778 if(m_subtitleCache.Lookup(entry, sub))
2780 if(sub->m_fAnimated) {delete sub; sub = NULL;}
2781 else return(sub);
2783 sub = new CSubtitle();
2784 if(!sub) return(NULL);
2785 CStringW str = GetStrW(entry, true);
2786 STSStyle stss, orgstss;
2787 GetStyle(entry, &stss);
2788 if (stss.fontScaleX == stss.fontScaleY && m_dPARCompensation != 1.0)
2790 switch(m_ePARCompensationType)
2792 case EPCTUpscale:
2793 if (m_dPARCompensation < 1.0)
2794 stss.fontScaleY /= m_dPARCompensation;
2795 else
2796 stss.fontScaleX *= m_dPARCompensation;
2797 break;
2798 case EPCTDownscale:
2799 if (m_dPARCompensation < 1.0)
2800 stss.fontScaleX *= m_dPARCompensation;
2801 else
2802 stss.fontScaleY /= m_dPARCompensation;
2803 break;
2804 case EPCTAccurateSize:
2805 stss.fontScaleX *= m_dPARCompensation;
2806 break;
2809 orgstss = stss;
2810 sub->m_clip.SetRect(0, 0, m_size.cx>>3, m_size.cy>>3);
2811 sub->m_scrAlignment = -stss.scrAlignment;
2812 sub->m_wrapStyle = m_defaultWrapStyle;
2813 sub->m_fAnimated = false;
2814 sub->m_relativeTo = stss.relativeTo;
2815 sub->m_scalex = m_dstScreenSize.cx > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Width() : m_size.cx) / (m_dstScreenSize.cx*8) : 1.0;
2816 sub->m_scaley = m_dstScreenSize.cy > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Height() : m_size.cy) / (m_dstScreenSize.cy*8) : 1.0;
2817 m_animStart = m_animEnd = 0;
2818 m_animAccel = 1;
2819 m_ktype = m_kstart = m_kend = 0;
2820 m_nPolygon = 0;
2821 m_polygonBaselineOffset = 0;
2822 ParseEffect(sub, m_entries.GetAt(entry).effect);
2823 while(!str.IsEmpty())
2825 bool fParsed = false;
2826 int i;
2827 if(str[0] == L'{' && (i = str.Find(L'}')) > 0)
2829 if(fParsed = ParseSSATag(sub, str.Mid(1, i-1), stss, orgstss))
2830 str = str.Mid(i+1);
2832 else if(str[0] == L'<' && (i = str.Find(L'>')) > 0)
2834 if(fParsed = ParseHtmlTag(sub, str.Mid(1, i-1), stss, orgstss))
2835 str = str.Mid(i+1);
2837 if(fParsed)
2839 i = str.FindOneOf(L"{<");
2840 if(i < 0) i = str.GetLength();
2841 if(i == 0) continue;
2843 else
2845 i = str.Mid(1).FindOneOf(L"{<");
2846 if(i < 0) i = str.GetLength()-1;
2847 i++;
2849 STSStyle tmp = stss;
2850 tmp.fontSize = sub->m_scaley*tmp.fontSize*64;
2851 tmp.fontSpacing = sub->m_scalex*tmp.fontSpacing*64;
2852 tmp.outlineWidthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2853 tmp.outlineWidthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2854 tmp.shadowDepthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2855 tmp.shadowDepthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2856 FwSTSStyle fw_tmp(tmp);
2857 if(m_nPolygon)
2859 ParsePolygon(sub, str.Left(i), fw_tmp);
2861 else
2863 ParseString(sub, str.Left(i), fw_tmp);
2865 str = str.Mid(i);
2867 sub->m_fAnimated2 |= sub->m_fAnimated;
2868 if( sub->m_effects[EF_FADE] || sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL]
2869 || sub->m_effects[EF_MOVE] )
2870 sub->m_fAnimated2 = true;
2871 // just a "work-around" solution... in most cases nobody will want to use \org together with moving but without rotating the subs
2872 if(sub->m_effects[EF_ORG] && (sub->m_effects[EF_MOVE] || sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL]))
2873 sub->m_fAnimated = true;
2874 sub->m_scrAlignment = abs(sub->m_scrAlignment);
2875 STSEntry stse = m_entries.GetAt(entry);
2876 CRect marginRect = stse.marginRect;
2877 if(marginRect.left == 0) marginRect.left = orgstss.marginRect.get().left;
2878 if(marginRect.top == 0) marginRect.top = orgstss.marginRect.get().top;
2879 if(marginRect.right == 0) marginRect.right = orgstss.marginRect.get().right;
2880 if(marginRect.bottom == 0) marginRect.bottom = orgstss.marginRect.get().bottom;
2881 marginRect.left = (int)(sub->m_scalex*marginRect.left*8);
2882 marginRect.top = (int)(sub->m_scaley*marginRect.top*8);
2883 marginRect.right = (int)(sub->m_scalex*marginRect.right*8);
2884 marginRect.bottom = (int)(sub->m_scaley*marginRect.bottom*8);
2885 if(stss.relativeTo == 1)
2887 marginRect.left += m_vidrect.left;
2888 marginRect.top += m_vidrect.top;
2889 marginRect.right += m_size.cx - m_vidrect.right;
2890 marginRect.bottom += m_size.cy - m_vidrect.bottom;
2892 sub->CreateClippers(m_size);
2893 sub->MakeLines(m_size, marginRect);
2894 m_subtitleCache[entry] = sub;
2895 return(sub);
2900 STDMETHODIMP CRenderedTextSubtitle::NonDelegatingQueryInterface(REFIID riid, void** ppv)
2902 CheckPointer(ppv, E_POINTER);
2903 *ppv = NULL;
2904 return
2905 QI(IPersist)
2906 QI(ISubStream)
2907 QI(ISubPicProvider)
2908 QI(ISubPicProviderEx)
2909 __super::NonDelegatingQueryInterface(riid, ppv);
2912 // ISubPicProvider
2914 STDMETHODIMP_(POSITION) CRenderedTextSubtitle::GetStartPosition(REFERENCE_TIME rt, double fps)
2916 //DbgLog((LOG_TRACE, 3, "rt:%lu", (ULONG)rt/10000));
2917 m_fps = fps;//fix me: check is fps changed and do some re-init thing
2918 int iSegment;
2919 int subIndex = 1;//If a segment has animate effect then it corresponds to several subpics.
2920 //subIndex, 1 based, indicates which subpic the result corresponds to.
2921 rt /= 10000i64;
2922 const STSSegment *stss = SearchSubs((int)rt, fps, &iSegment, NULL);
2923 if(stss==NULL)
2924 return NULL;
2925 else if(stss->animated)
2927 int start = TranslateSegmentStart(iSegment, fps);
2928 if(rt > start)
2929 subIndex = (rt-start)/RTS_ANIMATE_SUBPIC_DUR + 1;
2931 //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));
2932 return (POSITION)(subIndex | (iSegment<<RTS_POS_SEGMENT_INDEX_BITS));
2933 //if(iSegment < 0) iSegment = 0;
2934 //return(GetNext((POSITION)iSegment));
2937 STDMETHODIMP_(POSITION) CRenderedTextSubtitle::GetNext(POSITION pos)
2939 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2940 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2941 const STSSegment *stss = GetSegment(iSegment);
2942 ASSERT(stss!=NULL && stss->subs.GetCount()>0);
2943 //DbgLog((LOG_TRACE, 3, "stss:%x count:%d", stss, stss->subs.GetCount()));
2944 if(!stss->animated)
2946 iSegment++;
2947 subIndex = 1;
2949 else
2951 int start, end;
2952 TranslateSegmentStartEnd(iSegment, m_fps, start, end);
2953 if(start+RTS_ANIMATE_SUBPIC_DUR*subIndex < end)
2954 subIndex++;
2955 else
2957 iSegment++;
2958 subIndex = 1;
2961 if(GetSegment(iSegment) != NULL)
2963 ASSERT(GetSegment(iSegment)->subs.GetCount()>0);
2964 return (POSITION)(subIndex | (iSegment<<RTS_POS_SEGMENT_INDEX_BITS));
2966 else
2967 return NULL;
2970 //@return: <0 if segment not found
2971 STDMETHODIMP_(REFERENCE_TIME) CRenderedTextSubtitle::GetStart(POSITION pos, double fps)
2973 //return(10000i64 * TranslateSegmentStart((int)pos-1, fps));
2974 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2975 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2976 int start = TranslateSegmentStart(iSegment, fps);
2977 const STSSegment *stss = GetSegment(iSegment);
2978 if(stss!=NULL)
2980 return (start + (subIndex-1)*RTS_ANIMATE_SUBPIC_DUR)*10000i64;
2982 else
2984 return -1;
2988 //@return: <0 if segment not found
2989 STDMETHODIMP_(REFERENCE_TIME) CRenderedTextSubtitle::GetStop(POSITION pos, double fps)
2991 // return(10000i64 * TranslateSegmentEnd((int)pos-1, fps));
2992 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2993 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2994 int start, end, ret;
2995 TranslateSegmentStartEnd(iSegment, fps, start, end);
2996 const STSSegment *stss = GetSegment(iSegment);
2997 if(stss!=NULL)
2999 if(!stss->animated)
3000 ret = end;
3001 else
3003 ret = start+subIndex*RTS_ANIMATE_SUBPIC_DUR;
3004 if(ret > end)
3005 ret = end;
3007 return ret*10000i64;
3009 else
3010 return -1;
3013 //@start, @stop: -1 if segment not found; @stop may < @start if subIndex exceed uppper bound
3014 STDMETHODIMP_(VOID) CRenderedTextSubtitle::GetStartStop(POSITION pos, double fps, /*out*/REFERENCE_TIME &start, /*out*/REFERENCE_TIME &stop)
3016 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3017 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
3018 int tempStart, tempEnd;
3019 TranslateSegmentStartEnd(iSegment, fps, tempStart, tempEnd);
3020 start = tempStart;
3021 stop = tempEnd;
3022 const STSSegment *stss = GetSegment(iSegment);
3023 if(stss!=NULL)
3025 if(stss->animated)
3027 start += (subIndex-1)*RTS_ANIMATE_SUBPIC_DUR;
3028 if(start+RTS_ANIMATE_SUBPIC_DUR < stop)
3029 stop = start+RTS_ANIMATE_SUBPIC_DUR;
3031 //DbgLog((LOG_TRACE, 3, "animated:%d seg:%d idx:%d start:%d stop:%lu", stss->animated, iSegment, subIndex, (ULONG)start, (ULONG)stop));
3032 start *= 10000i64;
3033 stop *= 10000i64;
3035 else
3037 start = -1;
3038 stop = -1;
3042 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsAnimated(POSITION pos)
3044 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3045 if(iSegment>=0 && iSegment<m_segments.GetCount())
3046 return m_segments[iSegment].animated;
3047 else
3048 return false;
3049 //return(true);
3052 struct LSub {int idx, layer, readorder;};
3054 static int lscomp(const void* ls1, const void* ls2)
3056 int ret = ((LSub*)ls1)->layer - ((LSub*)ls2)->layer;
3057 if(!ret) ret = ((LSub*)ls1)->readorder - ((LSub*)ls2)->readorder;
3058 return(ret);
3061 STDMETHODIMP CRenderedTextSubtitle::RenderEx(SubPicDesc& spd, REFERENCE_TIME rt, double fps, CAtlList<CRect>& rectList)
3063 CRect bbox2(0,0,0,0);
3064 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))
3065 Init(CSize(spd.w, spd.h), spd.vidrect);
3066 int t = (int)(rt / 10000);
3067 int segment;
3068 //const
3069 STSSegment* stss = SearchSubs2(t, fps, &segment);
3070 if(!stss) return S_FALSE;
3071 // clear any cached subs not in the range of +/-30secs measured from the segment's bounds
3073 POSITION pos = m_subtitleCache.GetStartPosition();
3074 while(pos)
3076 int key;
3077 CSubtitle* value;
3078 m_subtitleCache.GetNextAssoc(pos, key, value);
3079 STSEntry& stse = m_entries.GetAt(key);
3080 if(stse.end <= (t-30000) || stse.start > (t+30000))
3082 delete value;
3083 m_subtitleCache.RemoveKey(key);
3084 pos = m_subtitleCache.GetStartPosition();
3088 m_sla.AdvanceToSegment(segment, stss->subs);
3089 CAtlArray<LSub> subs;
3090 for(int i = 0, j = stss->subs.GetCount(); i < j; i++)
3092 LSub ls;
3093 ls.idx = stss->subs[i];
3094 ls.layer = m_entries.GetAt(stss->subs[i]).layer;
3095 ls.readorder = m_entries.GetAt(stss->subs[i]).readorder;
3096 subs.Add(ls);
3098 qsort(subs.GetData(), subs.GetCount(), sizeof(LSub), lscomp);
3100 CompositeDrawItemList drawItemList;
3101 for(int i = 0, j = subs.GetCount(); i < j; i++)
3103 int entry = subs[i].idx;
3104 STSEntry stse = m_entries.GetAt(entry);
3106 int start = TranslateStart(entry, fps);
3107 m_time = t - start;
3108 m_delay = TranslateEnd(entry, fps) - start;
3110 CSubtitle* s = GetSubtitle(entry);
3111 if(!s) continue;
3112 stss->animated |= s->m_fAnimated2;
3113 CRect clipRect = s->m_clip;
3114 CRect r = s->m_rect;
3115 CSize spaceNeeded = r.Size();
3116 // apply the effects
3117 bool fPosOverride = false, fOrgOverride = false;
3118 int alpha = 0x00;
3119 CPoint org2;
3120 for(int k = 0; k < EF_NUMBEROFEFFECTS; k++)
3122 if(!s->m_effects[k]) continue;
3123 switch(k)
3125 case EF_MOVE: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3], t1=t[0], t2=t[1])}
3127 CPoint p;
3128 CPoint p1(s->m_effects[k]->param[0], s->m_effects[k]->param[1]);
3129 CPoint p2(s->m_effects[k]->param[2], s->m_effects[k]->param[3]);
3130 int t1 = s->m_effects[k]->t[0];
3131 int t2 = s->m_effects[k]->t[1];
3132 if(t2 < t1) {int t = t1; t1 = t2; t2 = t;}
3133 if(t1 <= 0 && t2 <= 0) {t1 = 0; t2 = m_delay;}
3134 if(m_time <= t1) p = p1;
3135 else if (p1 == p2) p = p1;
3136 else if(t1 < m_time && m_time < t2)
3138 double t = 1.0*(m_time-t1)/(t2-t1);
3139 p.x = (int)((1-t)*p1.x + t*p2.x);
3140 p.y = (int)((1-t)*p1.y + t*p2.y);
3142 else p = p2;
3143 r = CRect(
3144 CPoint((s->m_scrAlignment%3) == 1 ? p.x : (s->m_scrAlignment%3) == 0 ? p.x - spaceNeeded.cx : p.x - (spaceNeeded.cx+1)/2,
3145 s->m_scrAlignment <= 3 ? p.y - spaceNeeded.cy : s->m_scrAlignment <= 6 ? p.y - (spaceNeeded.cy+1)/2 : p.y),
3146 spaceNeeded);
3147 if(s->m_relativeTo == 1)
3148 r.OffsetRect(m_vidrect.TopLeft());
3149 fPosOverride = true;
3151 break;
3152 case EF_ORG: // {\org(x=param[0], y=param[1])}
3154 org2 = CPoint(s->m_effects[k]->param[0], s->m_effects[k]->param[1]);
3155 fOrgOverride = true;
3157 break;
3158 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])
3160 int t1 = s->m_effects[k]->t[0];
3161 int t2 = s->m_effects[k]->t[1];
3162 int t3 = s->m_effects[k]->t[2];
3163 int t4 = s->m_effects[k]->t[3];
3164 if(t1 == -1 && t4 == -1) {t1 = 0; t3 = m_delay-t3; t4 = m_delay;}
3165 if(m_time < t1) alpha = s->m_effects[k]->param[0];
3166 else if(m_time >= t1 && m_time < t2)
3168 double t = 1.0 * (m_time - t1) / (t2 - t1);
3169 alpha = (int)(s->m_effects[k]->param[0]*(1-t) + s->m_effects[k]->param[1]*t);
3171 else if(m_time >= t2 && m_time < t3) alpha = s->m_effects[k]->param[1];
3172 else if(m_time >= t3 && m_time < t4)
3174 double t = 1.0 * (m_time - t3) / (t4 - t3);
3175 alpha = (int)(s->m_effects[k]->param[1]*(1-t) + s->m_effects[k]->param[2]*t);
3177 else if(m_time >= t4) alpha = s->m_effects[k]->param[2];
3179 break;
3180 case EF_BANNER: // Banner;delay=param[0][;leftoright=param[1];fadeawaywidth=param[2]]
3182 int left = s->m_relativeTo == 1 ? m_vidrect.left : 0,
3183 right = s->m_relativeTo == 1 ? m_vidrect.right : m_size.cx;
3184 r.left = !!s->m_effects[k]->param[1]
3185 ? (left/*marginRect.left*/ - spaceNeeded.cx) + (int)(m_time*8.0/s->m_effects[k]->param[0])
3186 : (right /*- marginRect.right*/) - (int)(m_time*8.0/s->m_effects[k]->param[0]);
3187 r.right = r.left + spaceNeeded.cx;
3188 clipRect &= CRect(left>>3, clipRect.top, right>>3, clipRect.bottom);
3189 fPosOverride = true;
3191 break;
3192 case EF_SCROLL: // Scroll up/down(toptobottom=param[3]);top=param[0];bottom=param[1];delay=param[2][;fadeawayheight=param[4]]
3194 r.top = !!s->m_effects[k]->param[3]
3195 ? s->m_effects[k]->param[0] + (int)(m_time*8.0/s->m_effects[k]->param[2]) - spaceNeeded.cy
3196 : s->m_effects[k]->param[1] - (int)(m_time*8.0/s->m_effects[k]->param[2]);
3197 r.bottom = r.top + spaceNeeded.cy;
3198 CRect cr(0, (s->m_effects[k]->param[0] + 4) >> 3, spd.w, (s->m_effects[k]->param[1] + 4) >> 3);
3199 if(s->m_relativeTo == 1)
3200 r.top += m_vidrect.top,
3201 r.bottom += m_vidrect.top,
3202 cr.top += m_vidrect.top>>3,
3203 cr.bottom += m_vidrect.top>>3;
3204 clipRect &= cr;
3205 fPosOverride = true;
3207 break;
3208 default:
3209 break;
3212 if(!fPosOverride && !fOrgOverride && !s->m_fAnimated)
3213 r = m_sla.AllocRect(s, segment, entry, stse.layer, m_collisions);
3214 CPoint org;
3215 org.x = (s->m_scrAlignment%3) == 1 ? r.left : (s->m_scrAlignment%3) == 2 ? r.CenterPoint().x : r.right;
3216 org.y = s->m_scrAlignment <= 3 ? r.bottom : s->m_scrAlignment <= 6 ? r.CenterPoint().y : r.top;
3217 if(!fOrgOverride) org2 = org;
3218 SharedArrayByte pAlphaMask;
3219 if( s->m_pClipper )
3220 pAlphaMask = s->m_pClipper->m_pAlphaMask;
3221 CPoint p, p2(0, r.top);
3222 POSITION pos;
3223 p = p2;
3224 // Rectangles for inverse clip
3225 CRect iclipRect[4];
3226 iclipRect[0] = CRect(0, 0, spd.w, clipRect.top);
3227 iclipRect[1] = CRect(0, clipRect.top, clipRect.left, clipRect.bottom);
3228 iclipRect[2] = CRect(clipRect.right, clipRect.top, spd.w, clipRect.bottom);
3229 iclipRect[3] = CRect(0, clipRect.bottom, spd.w, spd.h);
3230 int dbgTest = 0;
3231 bbox2 = CRect(0,0,0,0);
3232 pos = s->GetHeadLinePosition();
3233 while(pos)
3235 CLine* l = s->GetNextLine(pos);
3236 p.x = (s->m_scrAlignment%3) == 1 ? org.x
3237 : (s->m_scrAlignment%3) == 0 ? org.x - l->m_width
3238 : org.x - (l->m_width/2);
3240 CompositeDrawItemList tmpDrawItemList;
3241 if (s->m_clipInverse)
3243 for (int i=0;i<l->GetWordCount();i++)
3245 tmpDrawItemList.AddTail();
3246 tmpDrawItemList.AddTail();
3247 tmpDrawItemList.AddTail();
3248 tmpDrawItemList.AddTail();
3250 bbox2 |= l->PaintShadow(&tmpDrawItemList, spd, iclipRect[0], pAlphaMask, p, org2, m_time, alpha);
3251 bbox2 |= l->PaintShadow(&tmpDrawItemList, spd, iclipRect[1], pAlphaMask, p, org2, m_time, alpha);
3252 bbox2 |= l->PaintShadow(&tmpDrawItemList, spd, iclipRect[2], pAlphaMask, p, org2, m_time, alpha);
3253 bbox2 |= l->PaintShadow(&tmpDrawItemList, spd, iclipRect[3], pAlphaMask, p, org2, m_time, alpha);
3255 bbox2 |= l->PaintOutline(&tmpDrawItemList, spd, iclipRect[0], pAlphaMask, p, org2, m_time, alpha);
3256 bbox2 |= l->PaintOutline(&tmpDrawItemList, spd, iclipRect[1], pAlphaMask, p, org2, m_time, alpha);
3257 bbox2 |= l->PaintOutline(&tmpDrawItemList, spd, iclipRect[2], pAlphaMask, p, org2, m_time, alpha);
3258 bbox2 |= l->PaintOutline(&tmpDrawItemList, spd, iclipRect[3], pAlphaMask, p, org2, m_time, alpha);
3260 bbox2 |= l->PaintBody(&tmpDrawItemList, spd, iclipRect[0], pAlphaMask, p, org2, m_time, alpha);
3261 bbox2 |= l->PaintBody(&tmpDrawItemList, spd, iclipRect[1], pAlphaMask, p, org2, m_time, alpha);
3262 bbox2 |= l->PaintBody(&tmpDrawItemList, spd, iclipRect[2], pAlphaMask, p, org2, m_time, alpha);
3263 bbox2 |= l->PaintBody(&tmpDrawItemList, spd, iclipRect[3], pAlphaMask, p, org2, m_time, alpha);
3265 else
3267 for (int i=0;i<l->GetWordCount();i++)
3269 tmpDrawItemList.AddTail();
3271 bbox2 |= l->PaintShadow(&tmpDrawItemList, spd, clipRect, pAlphaMask, p, org2, m_time, alpha);
3273 bbox2 |= l->PaintOutline(&tmpDrawItemList, spd, clipRect, pAlphaMask, p, org2, m_time, alpha);
3275 bbox2 |= l->PaintBody(&tmpDrawItemList, spd, clipRect, pAlphaMask, p, org2, m_time, alpha);
3278 drawItemList.AddTailList(&tmpDrawItemList);
3279 p.y += l->m_ascent + l->m_descent;
3281 rectList.AddTail(bbox2);
3284 Draw(spd, drawItemList);
3285 return (subs.GetCount() && !rectList.IsEmpty()) ? S_OK : S_FALSE;
3289 STDMETHODIMP CRenderedTextSubtitle::Render(SubPicDesc& spd, REFERENCE_TIME rt, double fps, RECT& bbox)
3291 CAtlList<CRect> rectList;
3292 HRESULT result = RenderEx(spd, rt, fps, rectList);
3293 POSITION pos = rectList.GetHeadPosition();
3294 CRect bbox2(0,0,0,0);
3295 while(pos!=NULL)
3297 bbox2 |= rectList.GetNext(pos);
3299 bbox = bbox2;
3300 return result;
3303 // IPersist
3305 STDMETHODIMP CRenderedTextSubtitle::GetClassID(CLSID* pClassID)
3307 return pClassID ? *pClassID = __uuidof(this), S_OK : E_POINTER;
3310 // ISubStream
3312 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStreamCount()
3314 return(1);
3317 STDMETHODIMP CRenderedTextSubtitle::GetStreamInfo(int iStream, WCHAR** ppName, LCID* pLCID)
3319 if(iStream != 0) return E_INVALIDARG;
3320 if(ppName)
3322 if(!(*ppName = (WCHAR*)CoTaskMemAlloc((m_name.GetLength()+1)*sizeof(WCHAR))))
3323 return E_OUTOFMEMORY;
3324 wcscpy(*ppName, CStringW(m_name));
3326 if(pLCID)
3328 *pLCID = 0; // TODO
3330 return S_OK;
3333 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStream()
3335 return(0);
3338 STDMETHODIMP CRenderedTextSubtitle::SetStream(int iStream)
3340 return iStream == 0 ? S_OK : E_FAIL;
3343 STDMETHODIMP CRenderedTextSubtitle::Reload()
3345 CFileStatus s;
3346 if(!CFile::GetStatus(m_path, s)) return E_FAIL;
3347 return !m_path.IsEmpty() && Open(m_path, DEFAULT_CHARSET) ? S_OK : E_FAIL;
3350 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsColorTypeSupported( int type )
3352 return type==MSP_AY11 ||
3353 type==MSP_AYUV ||
3354 type==MSP_AUYV ||
3355 type==MSP_RGBA;
3358 void CRenderedTextSubtitle::Draw( SubPicDesc& spd, CompositeDrawItemList& drawItemList )
3360 POSITION pos = drawItemList.GetHeadPosition();
3361 while(pos)
3363 CompositeDrawItem& draw_item = drawItemList.GetNext(pos);
3364 if(draw_item.shadow)
3365 Rasterizer::Draw( spd, *draw_item.shadow );
3367 pos = drawItemList.GetHeadPosition();
3368 while(pos)
3370 CompositeDrawItem& draw_item = drawItemList.GetNext(pos);
3371 if(draw_item.outline)
3372 Rasterizer::Draw( spd, *draw_item.outline );
3374 pos = drawItemList.GetHeadPosition();
3375 while(pos)
3377 CompositeDrawItem& draw_item = drawItemList.GetNext(pos);
3378 if(draw_item.body)
3379 Rasterizer::Draw( spd, *draw_item.body );