Minor refactor.
[xy_vsfilter.git] / src / subtitles / RTS.cpp
bloba14caf996d26b24e065599e242466de5034040e3
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 m_width = 0;
161 CWord::CWord( const CWord& src)
163 m_str = src.m_str;
164 m_fWhiteSpaceChar = src.m_fWhiteSpaceChar;
165 m_fLineBreak = src.m_fLineBreak;
166 m_style = src.m_style;
167 m_pOpaqueBox = src.m_pOpaqueBox;//allow since it is shared_ptr
168 m_ktype = src.m_ktype;
169 m_kstart = src.m_kstart;
170 m_kend = src.m_kend;
171 m_width = src.m_width;
172 m_ascent = src.m_ascent;
173 m_descent = src.m_descent;
176 CWord::~CWord()
178 //if(m_pOpaqueBox) delete m_pOpaqueBox;
181 bool CWord::Append(const SharedPtrCWord& w)
183 if(!(m_style == w->m_style)
184 || m_fLineBreak || w->m_fLineBreak
185 || w->m_kstart != w->m_kend || m_ktype != w->m_ktype) return(false);
186 m_fWhiteSpaceChar = m_fWhiteSpaceChar && w->m_fWhiteSpaceChar;
187 m_str += w->m_str;
188 m_width += w->m_width;
189 return(true);
192 void CWord::Paint( SharedPtrCWord word, const CPoint& p, const CPoint& trans_org, OverlayList* overlay_list )
194 if(!word->m_str || overlay_list==NULL) return;
195 bool error = false;
198 CPoint trans_org2 = trans_org;
199 bool need_transform = word->NeedTransform();
200 if(!need_transform)
202 trans_org2.x=0;
203 trans_org2.y=0;
206 if( SubpixelPositionControler::GetGlobalControler().UseBilinearShift() )
208 CPoint psub_true( (p.x&SubpixelPositionControler::EIGHT_X_EIGHT_MASK), (p.y&SubpixelPositionControler::EIGHT_X_EIGHT_MASK) );
209 OverlayKey sub_key(*word, psub_true, trans_org2);
211 OverlayMruCache* overlay_cache = CacheManager::GetSubpixelVarianceCache();
213 POSITION pos = overlay_cache->Lookup(sub_key);
214 if(pos!=NULL)
216 overlay_list->overlay = overlay_cache->GetAt(pos);
217 overlay_cache->UpdateCache( pos );
220 if( !overlay_list->overlay )
222 CPoint psub = SubpixelPositionControler::GetGlobalControler().GetSubpixel(p);
223 OverlayKey overlay_key(*word, psub, trans_org2);
224 OverlayMruCache* overlay_cache = CacheManager::GetOverlayMruCache();
225 POSITION pos = overlay_cache->Lookup(overlay_key);
226 if(pos==NULL)
228 if( !word->DoPaint(psub, trans_org2, &(overlay_list->overlay), overlay_key) )
230 error = true;
231 break;
233 overlay_cache->UpdateCache(overlay_key, overlay_list->overlay);
235 else
237 overlay_list->overlay = overlay_cache->GetAt(pos);
238 overlay_cache->UpdateCache( pos );
240 if( SubpixelPositionControler::GetGlobalControler().UseBilinearShift()
241 && (psub.x!=(p.x&SubpixelPositionControler::EIGHT_X_EIGHT_MASK)
242 || psub.y!=(p.y&SubpixelPositionControler::EIGHT_X_EIGHT_MASK)) )
244 overlay_list->overlay.reset(overlay_list->overlay->GetSubpixelVariance((p.x&SubpixelPositionControler::EIGHT_X_EIGHT_MASK) - psub.x,
245 (p.y&SubpixelPositionControler::EIGHT_X_EIGHT_MASK) - psub.y));
246 CPoint psub_true( (p.x&SubpixelPositionControler::EIGHT_X_EIGHT_MASK), (p.y&SubpixelPositionControler::EIGHT_X_EIGHT_MASK) );
247 OverlayKey sub_key(*word, psub_true, trans_org2);
248 OverlayMruCache* overlay_cache = CacheManager::GetSubpixelVarianceCache();
249 overlay_cache->UpdateCache(sub_key, overlay_list->overlay);
253 if(word->m_style.get().borderStyle == 1)
255 if(!word->CreateOpaqueBox())
257 error = true;
258 break;
260 overlay_list->next = new OverlayList();
261 Paint(word->m_pOpaqueBox, p, trans_org, overlay_list->next);
263 } while(false);
264 if(error)
266 overlay_list->overlay.reset( new Overlay() );
270 bool CWord::DoPaint(const CPoint& psub, const CPoint& trans_org, SharedPtrOverlay* overlay, const OverlayKey& key)
272 //overlay->reset(new Overlay());
273 OverlayNoBlurMruCache* overlay_no_blur_cache = CacheManager::GetOverlayNoBlurMruCache();
274 POSITION pos = overlay_no_blur_cache->Lookup(key);
276 SharedPtrOverlay raterize_result;
277 if(pos==NULL)
279 raterize_result.reset(new Overlay());
281 SharedPtrConstScanLineData scan_line_data;
282 ScanLineDataMruCache* scan_line_data_cache = CacheManager::GetScanLineDataMruCache();
283 POSITION pos_scan_line_data = scan_line_data_cache->Lookup(key);
284 if(pos_scan_line_data==NULL)
286 //get outline path, if not cached, create it and cache a copy, else copy from cache
287 SharedPtrPathData path_data(new PathData());
288 PathDataMruCache* path_data_cache = CacheManager::GetPathDataMruCache();
289 POSITION pos_path = path_data_cache->Lookup(key);
290 if(pos_path==NULL)
292 if(!CreatePath(path_data))
294 return false;
297 SharedPtrPathData data(new PathData());
298 *data = *path_data;//important! copy not ref
299 path_data_cache->UpdateCache(key, data);
301 else
303 *path_data = *(path_data_cache->GetAt(pos_path)); //important! copy not ref
304 path_data_cache->UpdateCache( pos_path );
307 bool need_transform = NeedTransform();
308 if(need_transform)
309 Transform(path_data, CPoint(trans_org.x*8, trans_org.y*8));
311 SharedPtrScanLineData tmp(new ScanLineData());
312 if(!tmp->ScanConvert(path_data))
314 return false;
316 if(m_style.get().borderStyle == 0 && (m_style.get().outlineWidthX+m_style.get().outlineWidthY > 0))
318 if(!tmp->CreateWidenedRegion(static_cast<int>(m_style.get().outlineWidthX+0.5),
319 static_cast<int>(m_style.get().outlineWidthY+0.5)))
321 return false;
324 else if(m_style.get().borderStyle == 1)
326 if(!CreateOpaqueBox())
328 return false;
332 scan_line_data_cache->UpdateCache(key, tmp);
333 scan_line_data = tmp;
335 else
337 scan_line_data = scan_line_data_cache->GetAt(pos_scan_line_data);
338 scan_line_data_cache->UpdateCache( pos_scan_line_data );
340 if(!Rasterizer::Rasterize(*scan_line_data, psub.x, psub.y, raterize_result))
342 return false;
345 overlay_no_blur_cache->UpdateCache(key, raterize_result);
347 else
349 raterize_result = overlay_no_blur_cache->GetAt(pos);
350 overlay_no_blur_cache->UpdateCache( pos );
352 if( m_style.get().fBlur>0 || m_style.get().fGaussianBlur>0.000001 )
354 overlay->reset(new Overlay());
355 if(!Rasterizer::Blur(*raterize_result, m_style.get().fBlur, m_style.get().fGaussianBlur, *overlay))
357 *overlay = raterize_result;
360 else
362 *overlay = raterize_result;
364 return true;
367 bool CWord::NeedTransform()
369 return (fabs(m_style.get().fontScaleX - 100) > 0.000001) ||
370 (fabs(m_style.get().fontScaleY - 100) > 0.000001) ||
371 (fabs(m_style.get().fontAngleX) > 0.000001) ||
372 (fabs(m_style.get().fontAngleY) > 0.000001) ||
373 (fabs(m_style.get().fontAngleZ) > 0.000001) ||
374 (fabs(m_style.get().fontShiftX) > 0.000001) ||
375 (fabs(m_style.get().fontShiftY) > 0.000001);
378 void CWord::Transform(SharedPtrPathData path_data, const CPoint& org)
380 //// CPUID from VDub
381 //bool fSSE2 = !!(g_cpuid.m_flags & CCpuID::sse2);
383 //if(fSSE2) { // SSE code
384 // Transform_SSE2(path_data, org);
385 //} else // C-code
386 Transform_C(path_data, org);
389 void CWord::Transform_C(const SharedPtrPathData& path_data, const CPoint &org )
391 double scalex = m_style.get().fontScaleX/100;
392 double scaley = m_style.get().fontScaleY/100;
394 double caz = cos((3.1415/180)*m_style.get().fontAngleZ);
395 double saz = sin((3.1415/180)*m_style.get().fontAngleZ);
396 double cax = cos((3.1415/180)*m_style.get().fontAngleX);
397 double sax = sin((3.1415/180)*m_style.get().fontAngleX);
398 double cay = cos((3.1415/180)*m_style.get().fontAngleY);
399 double say = sin((3.1415/180)*m_style.get().fontAngleY);
401 #ifdef _VSMOD
402 // patch m003. random text points
403 double xrnd = m_style.get().mod_rand.X*100;
404 double yrnd = m_style.get().mod_rand.Y*100;
405 double zrnd = m_style.get().mod_rand.Z*100;
407 srand(m_style.get().mod_rand.Seed);
409 // patch m008. distort
410 int xsz,ysz;
411 double dst1x,dst1y,dst2x,dst2y,dst3x,dst3y;
412 int minx = INT_MAX, miny = INT_MAX, maxx = -INT_MAX, maxy = -INT_MAX;
414 bool is_dist = m_style.get().mod_distort.enabled;
415 if (is_dist) {
416 for(int i = 0; i < path_data->mPathPoints; i++) {
417 if(minx > path_data->mpPathPoints[i].x) {
418 minx = path_data->mpPathPoints[i].x;
420 if(miny > path_data->mpPathPoints[i].y) {
421 miny = path_data->mpPathPoints[i].y;
423 if(maxx < path_data->mpPathPoints[i].x) {
424 maxx = path_data->mpPathPoints[i].x;
426 if(maxy < path_data->mpPathPoints[i].y) {
427 maxy = path_data->mpPathPoints[i].y;
431 xsz = max(maxx - minx, 0);
432 ysz = max(maxy - miny, 0);
434 dst1x = m_style.get().mod_distort.pointsx[0];
435 dst1y = m_style.get().mod_distort.pointsy[0];
436 dst2x = m_style.get().mod_distort.pointsx[1];
437 dst2y = m_style.get().mod_distort.pointsy[1];
438 dst3x = m_style.get().mod_distort.pointsx[2];
439 dst3y = m_style.get().mod_distort.pointsy[2];
441 #endif
443 for (int i = 0; i < path_data->mPathPoints; i++) {
444 double x, y, z, xx, yy, zz;
446 x = path_data->mpPathPoints[i].x;
447 y = path_data->mpPathPoints[i].y;
448 #ifdef _VSMOD
449 // patch m002. Z-coord
450 z = m_style.get().mod_z;
452 double u, v;
453 if (is_dist) {
454 u = (x-minx) / xsz;
455 v = (y-miny) / ysz;
457 x = minx+(0 + (dst1x - 0)*u + (dst3x-0)*v+(0+dst2x-dst1x-dst3x)*u*v)*xsz;
458 y = miny+(0 + (dst1y - 0)*u + (dst3y-0)*v+(0+dst2y-dst1y-dst3y)*u*v)*ysz;
459 //P = P0 + (P1 - P0)u + (P3 - P0)v + (P0 + P2 - P1 - P3)uv
462 // patch m003. random text points
463 x = xrnd > 0 ? (xrnd - rand() % (int)(xrnd * 2 + 1)) / 100.0 + x : x;
464 y = yrnd > 0 ? (yrnd - rand() % (int)(yrnd * 2 + 1)) / 100.0 + y : y;
465 z = zrnd > 0 ? (zrnd - rand() % (int)(zrnd * 2 + 1)) / 100.0 + z : z;
466 #else
467 z = 0;
468 #endif
469 double _x = x;
470 x = scalex * (x + m_style.get().fontShiftX * y) - org.x;
471 y = scaley * (y + m_style.get().fontShiftY * _x) - org.y;
473 xx = x*caz + y*saz;
474 yy = -(x*saz - y*caz);
475 zz = z;
477 x = xx;
478 y = yy*cax + zz*sax;
479 z = yy*sax - zz*cax;
481 xx = x*cay + z*say;
482 yy = y;
483 zz = x*say - z*cay;
485 zz = max(zz, -19000);
487 x = (xx * 20000) / (zz + 20000);
488 y = (yy * 20000) / (zz + 20000);
490 path_data->mpPathPoints[i].x = (LONG)(x + org.x + 0.5);
491 path_data->mpPathPoints[i].y = (LONG)(y + org.y + 0.5);
495 void CWord::Transform_SSE2(const SharedPtrPathData& path_data, const CPoint &org )
497 // __m128 union data type currently not supported with Intel C++ Compiler, so just call C version
498 #ifdef __ICL
499 Transform_C(org);
500 #else
501 // SSE code
502 // speed up ~1.5-1.7x
503 double scalex = m_style.get().fontScaleX/100;
504 double scaley = m_style.get().fontScaleY/100;
506 double caz = cos((3.1415/180)*m_style.get().fontAngleZ);
507 double saz = sin((3.1415/180)*m_style.get().fontAngleZ);
508 double cax = cos((3.1415/180)*m_style.get().fontAngleX);
509 double sax = sin((3.1415/180)*m_style.get().fontAngleX);
510 double cay = cos((3.1415/180)*m_style.get().fontAngleY);
511 double say = sin((3.1415/180)*m_style.get().fontAngleY);
513 __m128 __xshift = _mm_set_ps1(m_style.get().fontShiftX);
514 __m128 __yshift = _mm_set_ps1(m_style.get().fontShiftY);
516 __m128 __xorg = _mm_set_ps1(org.x);
517 __m128 __yorg = _mm_set_ps1(org.y);
519 __m128 __xscale = _mm_set_ps1(scalex);
520 __m128 __yscale = _mm_set_ps1(scaley);
522 #ifdef _VSMOD
523 // patch m003. random text points
524 double xrnd = m_style.get().mod_rand.X*100;
525 double yrnd = m_style.get().mod_rand.Y*100;
526 double zrnd = m_style.get().mod_rand.Z*100;
528 srand(m_style.get().mod_rand.Seed);
530 __m128 __xsz = _mm_setzero_ps();
531 __m128 __ysz = _mm_setzero_ps();
533 __m128 __dst1x, __dst1y, __dst213x, __dst213y, __dst3x, __dst3y;
535 __m128 __miny;
536 __m128 __minx = _mm_set_ps(INT_MAX, INT_MAX, 0, 0);
537 __m128 __max = _mm_set_ps(-INT_MAX, -INT_MAX, 1, 1);
539 bool is_dist = m_style.get().mod_distort.enabled;
540 if(is_dist) {
541 for(int i = 0; i < path_data->mPathPoints; i++) {
542 __m128 __point = _mm_set_ps(path_data->mpPathPoints[i].x, path_data->mpPathPoints[i].y, 0, 0);
543 __minx = _mm_min_ps(__minx, __point);
544 __max = _mm_max_ps(__max, __point);
547 __m128 __zero = _mm_setzero_ps();
548 __max = _mm_sub_ps(__max, __minx); // xsz, ysz, 1, 1
549 __max = _mm_max_ps(__max, __zero);
551 __xsz = _mm_shuffle_ps(__max, __max, _MM_SHUFFLE(3,3,3,3));
552 __ysz = _mm_shuffle_ps(__max, __max, _MM_SHUFFLE(2,2,2,2));
554 __miny = _mm_shuffle_ps(__minx, __minx, _MM_SHUFFLE(2,2,2,2));
555 __minx = _mm_shuffle_ps(__minx, __minx, _MM_SHUFFLE(3,3,3,3));
557 __dst1x = _mm_set_ps1(m_style.get().mod_distort.pointsx[0]);
558 __dst1y = _mm_set_ps1(m_style.get().mod_distort.pointsy[0]);
559 __dst3x = _mm_set_ps1(m_style.get().mod_distort.pointsx[2]);
560 __dst3y = _mm_set_ps1(m_style.get().mod_distort.pointsy[2]);
561 __dst213x = _mm_set_ps1(m_style.get().mod_distort.pointsx[1]); // 2 - 1 - 3
562 __dst213x = _mm_sub_ps(__dst213x, __dst1x);
563 __dst213x = _mm_sub_ps(__dst213x, __dst3x);
565 __dst213y = _mm_set_ps1(m_style.get().mod_distort.pointsy[1]);
566 __dst213x = _mm_sub_ps(__dst213y, __dst1y);
567 __dst213x = _mm_sub_ps(__dst213y, __dst3y);
569 #endif
571 __m128 __caz = _mm_set_ps1(caz);
572 __m128 __saz = _mm_set_ps1(saz);
573 __m128 __cax = _mm_set_ps1(cax);
574 __m128 __sax = _mm_set_ps1(sax);
575 __m128 __cay = _mm_set_ps1(cay);
576 __m128 __say = _mm_set_ps1(say);
578 // this can be paralleled for openmp
579 int mPathPointsD4 = path_data->mPathPoints / 4;
580 int mPathPointsM4 = path_data->mPathPoints % 4;
582 for(ptrdiff_t i = 0; i < mPathPointsD4 + 1; i++) {
583 POINT* const temp_points = path_data->mpPathPoints + 4 * i;
585 __m128 __pointx, __pointy;
586 // we can't use load .-.
587 if(i != mPathPointsD4) {
588 __pointx = _mm_set_ps(temp_points[0].x, temp_points[1].x, temp_points[2].x, temp_points[3].x);
589 __pointy = _mm_set_ps(temp_points[0].y, temp_points[1].y, temp_points[2].y, temp_points[3].y);
590 } else { // last cycle
591 switch(mPathPointsM4) {
592 default:
593 case 0:
594 continue;
595 case 1:
596 __pointx = _mm_set_ps(temp_points[0].x, 0, 0, 0);
597 __pointy = _mm_set_ps(temp_points[0].y, 0, 0, 0);
598 break;
599 case 2:
600 __pointx = _mm_set_ps(temp_points[0].x, temp_points[1].x, 0, 0);
601 __pointy = _mm_set_ps(temp_points[0].y, temp_points[1].y, 0, 0);
602 break;
603 case 3:
604 __pointx = _mm_set_ps(temp_points[0].x, temp_points[1].x, temp_points[2].x, 0);
605 __pointy = _mm_set_ps(temp_points[0].y, temp_points[1].y, temp_points[2].y, 0);
606 break;
610 #ifdef _VSMOD
611 __m128 __pointz = _mm_set_ps1(m_style.get().mod_z);
613 // distort
614 if(is_dist) {
615 //P = P0 + (P1 - P0)u + (P3 - P0)v + (P0 + P2 - P1 - P3)uv
616 __m128 __u = _mm_sub_ps(__pointx, __minx);
617 __m128 __v = _mm_sub_ps(__pointy, __miny);
618 __m128 __1_xsz = _mm_rcp_ps(__xsz);
619 __m128 __1_ysz = _mm_rcp_ps(__ysz);
620 __u = _mm_mul_ps(__u, __1_xsz);
621 __v = _mm_mul_ps(__v, __1_ysz);
623 // x
624 __pointx = _mm_mul_ps(__dst213x, __u);
625 __pointx = _mm_mul_ps(__pointx, __v);
627 __m128 __tmpx = _mm_mul_ps(__dst3x, __v);
628 __pointx = _mm_add_ps(__pointx, __tmpx);
629 __tmpx = _mm_mul_ps(__dst1x, __u);
630 __pointx = _mm_add_ps(__pointx, __tmpx);
632 __pointx = _mm_mul_ps(__pointx, __xsz);
633 __pointx = _mm_add_ps(__pointx, __minx);
635 // y
636 __pointy = _mm_mul_ps(__dst213y, __u);
637 __pointy = _mm_mul_ps(__pointy, __v);
639 __m128 __tmpy = _mm_mul_ps(__dst3y, __v);
640 __pointy = _mm_add_ps(__pointy, __tmpy);
641 __tmpy = _mm_mul_ps(__dst1y, __u);
642 __pointy = _mm_add_ps(__pointy, __tmpy);
644 __pointy = _mm_mul_ps(__pointy, __ysz);
645 __pointy = _mm_add_ps(__pointy, __miny);
648 // randomize
649 if(xrnd!=0 || yrnd!=0 || zrnd!=0) {
650 __declspec(align(16)) float rx[4], ry[4], rz[4];
651 for(int k=0; k<4; k++) {
652 rx[k] = xrnd > 0 ? (xrnd - rand() % (int)(xrnd * 2 + 1)) : 0;
653 ry[k] = yrnd > 0 ? (yrnd - rand() % (int)(yrnd * 2 + 1)) : 0;
654 rz[k] = zrnd > 0 ? (zrnd - rand() % (int)(zrnd * 2 + 1)) : 0;
656 __m128 __001 = _mm_set_ps1(0.01f);
658 if(xrnd!=0) {
659 __m128 __rx = _mm_load_ps(rx);
660 __rx = _mm_mul_ps(__rx, __001);
661 __pointx = _mm_add_ps(__pointx, __rx);
664 if(yrnd!=0) {
665 __m128 __ry = _mm_load_ps(ry);
666 __ry = _mm_mul_ps(__ry, __001);
667 __pointy = _mm_add_ps(__pointy, __ry);
670 if(zrnd!=0) {
671 __m128 __rz = _mm_load_ps(rz);
672 __rz = _mm_mul_ps(__rz, __001);
673 __pointz = _mm_add_ps(__pointz, __rz);
676 #else
677 __m128 __pointz = _mm_set_ps1(0);
678 #endif
680 // scale and shift
681 __m128 __tmpx;
682 if(m_style.get().fontShiftX!=0) {
683 __tmpx = _mm_mul_ps(__xshift, __pointy);
684 __tmpx = _mm_add_ps(__tmpx, __pointx);
685 } else {
686 __tmpx = __pointx;
688 __tmpx = _mm_mul_ps(__tmpx, __xscale);
689 __tmpx = _mm_sub_ps(__tmpx, __xorg);
691 __m128 __tmpy;
692 if(m_style.get().fontShiftY!=0) {
693 __tmpy = _mm_mul_ps(__yshift, __pointx);
694 __tmpy = _mm_add_ps(__tmpy, __pointy);
695 } else {
696 __tmpy = __pointy;
698 __tmpy = _mm_mul_ps(__tmpy, __yscale);
699 __tmpy = _mm_sub_ps(__tmpy, __yorg);
701 // rotate
702 __m128 __xx = _mm_mul_ps(__tmpx, __caz);
703 __m128 __yy = _mm_mul_ps(__tmpy, __saz);
704 __pointx = _mm_add_ps(__xx, __yy);
705 __xx = _mm_mul_ps(__tmpx, __saz);
706 __yy = _mm_mul_ps(__tmpy, __caz);
707 __pointy = _mm_sub_ps(__yy, __xx);
709 __m128 __zz = _mm_mul_ps(__pointz, __sax);
710 __yy = _mm_mul_ps(__pointy, __cax);
711 __pointy = _mm_add_ps(__yy, __zz);
712 __zz = _mm_mul_ps(__pointz, __cax);
713 __yy = _mm_mul_ps(__pointy, __sax);
714 __pointz = _mm_sub_ps(__zz, __yy);
716 __xx = _mm_mul_ps(__pointx, __cay);
717 __zz = _mm_mul_ps(__pointz, __say);
718 __pointx = _mm_add_ps(__xx, __zz);
719 __xx = _mm_mul_ps(__pointx, __say);
720 __zz = _mm_mul_ps(__pointz, __cay);
721 __pointz = _mm_sub_ps(__xx, __zz);
723 __zz = _mm_set_ps1(-19000);
724 __pointz = _mm_max_ps(__pointz, __zz);
726 __m128 __20000 = _mm_set_ps1(20000);
727 __zz = _mm_add_ps(__pointz, __20000);
728 __zz = _mm_rcp_ps(__zz);
730 __pointx = _mm_mul_ps(__pointx, __20000);
731 __pointx = _mm_mul_ps(__pointx, __zz);
733 __pointy = _mm_mul_ps(__pointy, __20000);
734 __pointy = _mm_mul_ps(__pointy, __zz);
736 __pointx = _mm_add_ps(__pointx, __xorg);
737 __pointy = _mm_add_ps(__pointy, __yorg);
739 __m128 __05 = _mm_set_ps1(0.5);
741 __pointx = _mm_add_ps(__pointx, __05);
742 __pointy = _mm_add_ps(__pointy, __05);
744 if(i == mPathPointsD4) { // last cycle
745 for(int k=0; k<mPathPointsM4; k++) {
746 temp_points[k].x = static_cast<LONG>(__pointx.m128_f32[3-k]);
747 temp_points[k].y = static_cast<LONG>(__pointy.m128_f32[3-k]);
749 } else {
750 for(int k=0; k<4; k++) {
751 temp_points[k].x = static_cast<LONG>(__pointx.m128_f32[3-k]);
752 temp_points[k].y = static_cast<LONG>(__pointy.m128_f32[3-k]);
756 #endif // __ICL
759 bool CWord::CreateOpaqueBox()
761 if(m_pOpaqueBox) return(true);
762 STSStyle style = m_style.get();
763 style.borderStyle = 0;
764 style.outlineWidthX = style.outlineWidthY = 0;
765 style.colors[0] = m_style.get().colors[2];
766 style.alpha[0] = m_style.get().alpha[2];
767 int w = (int)(m_style.get().outlineWidthX + 0.5);
768 int h = (int)(m_style.get().outlineWidthY + 0.5);
769 CStringW str;
770 str.Format(L"m %d %d l %d %d %d %d %d %d",
771 -w, -h,
772 m_width+w, -h,
773 m_width+w, m_ascent+m_descent+h,
774 -w, m_ascent+m_descent+h);
775 m_pOpaqueBox.reset( new CPolygon(FwSTSStyle(style), str, 0, 0, 0, 1.0/8, 1.0/8, 0) );
776 return(!!m_pOpaqueBox);
779 // CText
781 CText::CText(const FwSTSStyle& style, const CStringW& str, int ktype, int kstart, int kend)
782 : CWord(style, str, ktype, kstart, kend)
784 if(m_str == L" ")
786 m_fWhiteSpaceChar = true;
788 SharedPtrTextInfo text_info;
789 TextInfoCacheKey text_info_key;
790 text_info_key.m_str = m_str;
791 text_info_key.m_style = m_style;
792 TextInfoMruCache* text_info_cache = CacheManager::GetTextInfoCache();
793 POSITION pos = text_info_cache->Lookup(text_info_key);
794 if(pos==NULL)
796 TextInfo* tmp=new TextInfo();
797 GetTextInfo(tmp, m_style, m_str);
798 text_info.reset(tmp);
799 text_info_cache->UpdateCache(text_info_key, text_info);
801 else
803 text_info = text_info_cache->GetAt(pos);
804 text_info_cache->UpdateCache( pos );
806 this->m_ascent = text_info->m_ascent;
807 this->m_descent = text_info->m_descent;
808 this->m_width = text_info->m_width;
811 CText::CText( const CText& src ):CWord(src)
813 m_width = src.m_width;
816 SharedPtrCWord CText::Copy()
818 SharedPtrCWord result(new CText(*this));
819 return result;
822 bool CText::Append(const SharedPtrCWord& w)
824 return (w && CWord::Append(w));
827 bool CText::CreatePath(const SharedPtrPathData& path_data)
829 FwCMyFont font(m_style);
830 HFONT hOldFont = SelectFont(g_hDC, font.get());
831 int width = 0;
832 if(m_style.get().fontSpacing || (long)GetVersion() < 0)
834 bool bFirstPath = true;
835 for(LPCWSTR s = m_str; *s; s++)
837 CSize extent;
838 if(!GetTextExtentPoint32W(g_hDC, s, 1, &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return(false);}
839 path_data->PartialBeginPath(g_hDC, bFirstPath);
840 bFirstPath = false;
841 TextOutW(g_hDC, 0, 0, s, 1);
842 path_data->PartialEndPath(g_hDC, width, 0);
843 width += extent.cx + (int)m_style.get().fontSpacing;
846 else
848 CSize extent;
849 if(!GetTextExtentPoint32W(g_hDC, m_str, m_str.GetLength(), &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return(false);}
850 path_data->BeginPath(g_hDC);
851 TextOutW(g_hDC, 0, 0, m_str, m_str.GetLength());
852 path_data->EndPath(g_hDC);
854 SelectFont(g_hDC, hOldFont);
855 return(true);
858 void CText::GetTextInfo(TextInfo *output, const FwSTSStyle& style, const CStringW& str )
860 FwCMyFont font(style);
861 output->m_ascent = (int)(style.get().fontScaleY/100*font.get().m_ascent);
862 output->m_descent = (int)(style.get().fontScaleY/100*font.get().m_descent);
864 HFONT hOldFont = SelectFont(g_hDC, font.get());
865 if(style.get().fontSpacing || (long)GetVersion() < 0)
867 bool bFirstPath = true;
868 for(LPCWSTR s = str; *s; s++)
870 CSize extent;
871 if(!GetTextExtentPoint32W(g_hDC, s, 1, &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return;}
872 output->m_width += extent.cx + (int)style.get().fontSpacing;
874 // m_width -= (int)m_style.get().fontSpacing; // TODO: subtract only at the end of the line
876 else
878 CSize extent;
879 if(!GetTextExtentPoint32W(g_hDC, str, wcslen(str), &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return;}
880 output->m_width += extent.cx;
882 output->m_width = (int)(style.get().fontScaleX/100*output->m_width + 4) >> 3;
883 SelectFont(g_hDC, hOldFont);
886 // CPolygon
888 CPolygon::CPolygon(const FwSTSStyle& style, const CStringW& str, int ktype, int kstart, int kend, double scalex, double scaley, int baseline)
889 : CWord(style, str, ktype, kstart, kend)
890 , m_scalex(scalex), m_scaley(scaley), m_baseline(baseline)
892 ParseStr();
895 CPolygon::CPolygon(CPolygon& src) : CWord(src)
897 m_scalex = src.m_scalex;
898 m_scaley = src.m_scaley;
899 m_baseline = src.m_baseline;
900 m_width = src.m_width;
901 m_ascent = src.m_ascent;
902 m_descent = src.m_descent;
903 m_pathTypesOrg.Copy(src.m_pathTypesOrg);
904 m_pathPointsOrg.Copy(src.m_pathPointsOrg);
906 CPolygon::~CPolygon()
910 SharedPtrCWord CPolygon::Copy()
912 SharedPtrCWord result(DNew CPolygon(*this));
913 return result;
916 bool CPolygon::Append(const SharedPtrCWord& w)
918 // TODO
919 return(false);
922 bool CPolygon::GetLONG(CStringW& str, LONG& ret)
924 LPWSTR s = (LPWSTR)(LPCWSTR)str, e = s;
925 ret = wcstol(str, &e, 10);
926 str = str.Mid(e - s);
927 return(e > s);
930 bool CPolygon::GetPOINT(CStringW& str, POINT& ret)
932 return(GetLONG(str, ret.x) && GetLONG(str, ret.y));
935 bool CPolygon::ParseStr()
937 if(m_pathTypesOrg.GetCount() > 0) return(true);
938 CPoint p;
939 int j, lastsplinestart = -1, firstmoveto = -1, lastmoveto = -1;
940 CStringW str = m_str;
941 str.SpanIncluding(L"mnlbspc 0123456789");
942 str.Replace(L"m", L"*m");
943 str.Replace(L"n", L"*n");
944 str.Replace(L"l", L"*l");
945 str.Replace(L"b", L"*b");
946 str.Replace(L"s", L"*s");
947 str.Replace(L"p", L"*p");
948 str.Replace(L"c", L"*c");
949 int k = 0;
950 for(CStringW s = str.Tokenize(L"*", k); !s.IsEmpty(); s = str.Tokenize(L"*", k))
952 WCHAR c = s[0];
953 s.TrimLeft(L"mnlbspc ");
954 switch(c)
956 case 'm':
957 lastmoveto = m_pathTypesOrg.GetCount();
958 if(firstmoveto == -1) firstmoveto = lastmoveto;
959 while(GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_MOVETO); m_pathPointsOrg.Add(p);}
960 break;
961 case 'n':
962 while(GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_MOVETONC); m_pathPointsOrg.Add(p);}
963 break;
964 case 'l':
965 while(GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_LINETO); m_pathPointsOrg.Add(p);}
966 break;
967 case 'b':
968 j = m_pathTypesOrg.GetCount();
969 while(GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_BEZIERTO); m_pathPointsOrg.Add(p); j++;}
970 j = m_pathTypesOrg.GetCount() - ((m_pathTypesOrg.GetCount()-j)%3);
971 m_pathTypesOrg.SetCount(j);
972 m_pathPointsOrg.SetCount(j);
973 break;
974 case 's':
976 j = lastsplinestart = m_pathTypesOrg.GetCount();
977 int i = 3;
978 while(i-- && GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_BSPLINETO); m_pathPointsOrg.Add(p); j++;}
979 if(m_pathTypesOrg.GetCount()-lastsplinestart < 3) {m_pathTypesOrg.SetCount(lastsplinestart); m_pathPointsOrg.SetCount(lastsplinestart); lastsplinestart = -1;}
981 // no break here
982 case 'p':
983 while(GetPOINT(s, p)) {m_pathTypesOrg.Add(PT_BSPLINEPATCHTO); m_pathPointsOrg.Add(p); j++;}
984 break;
985 case 'c':
986 if(lastsplinestart > 0)
988 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
989 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
990 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
991 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)
992 m_pathPointsOrg.Add(p);
993 p = m_pathPointsOrg[lastsplinestart];
994 m_pathPointsOrg.Add(p);
995 p = m_pathPointsOrg[lastsplinestart+1];
996 m_pathPointsOrg.Add(p);
997 lastsplinestart = -1;
999 break;
1000 default:
1001 break;
1005 LPCWSTR str = m_str;
1006 while(*str)
1008 while(*str && *str != 'm' && *str != 'n' && *str != 'l' && *str != 'b' && *str != 's' && *str != 'p' && *str != 'c') str++;
1010 if(!*str) break;
1012 switch(*str++)
1014 case 'm':
1015 lastmoveto = m_pathTypesOrg.GetCount();
1016 if(firstmoveto == -1) firstmoveto = lastmoveto;
1017 while(GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_MOVETO); m_pathPointsOrg.Add(p);}
1018 break;
1019 case 'n':
1020 while(GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_MOVETONC); m_pathPointsOrg.Add(p);}
1021 break;
1022 case 'l':
1023 while(GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_LINETO); m_pathPointsOrg.Add(p);}
1024 break;
1025 case 'b':
1026 j = m_pathTypesOrg.GetCount();
1027 while(GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_BEZIERTO); m_pathPointsOrg.Add(p); j++;}
1028 j = m_pathTypesOrg.GetCount() - ((m_pathTypesOrg.GetCount()-j)%3);
1029 m_pathTypesOrg.SetCount(j); m_pathPointsOrg.SetCount(j);
1030 break;
1031 case 's':
1032 j = lastsplinestart = m_pathTypesOrg.GetCount();
1033 i = 3;
1034 while(i-- && GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_BSPLINETO); m_pathPointsOrg.Add(p); j++;}
1035 if(m_pathTypesOrg.GetCount()-lastsplinestart < 3) {m_pathTypesOrg.SetCount(lastsplinestart); m_pathPointsOrg.SetCount(lastsplinestart); lastsplinestart = -1;}
1036 // no break here
1037 case 'p':
1038 while(GetPOINT(str, p)) {m_pathTypesOrg.Add(PT_BSPLINEPATCHTO); m_pathPointsOrg.Add(p); j++;}
1039 break;
1040 case 'c':
1041 if(lastsplinestart > 0)
1043 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
1044 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
1045 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
1046 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)
1047 m_pathPointsOrg.Add(p);
1048 p = m_pathPointsOrg[lastsplinestart];
1049 m_pathPointsOrg.Add(p);
1050 p = m_pathPointsOrg[lastsplinestart+1];
1051 m_pathPointsOrg.Add(p);
1052 lastsplinestart = -1;
1054 break;
1055 default:
1056 break;
1059 if(firstmoveto > 0) break;
1062 if(lastmoveto == -1 || firstmoveto > 0)
1064 m_pathTypesOrg.RemoveAll();
1065 m_pathPointsOrg.RemoveAll();
1066 return(false);
1068 int minx = INT_MAX, miny = INT_MAX, maxx = -INT_MAX, maxy = -INT_MAX;
1069 for(size_t i = 0; i < m_pathTypesOrg.GetCount(); i++)
1071 m_pathPointsOrg[i].x = (int)(64 * m_scalex * m_pathPointsOrg[i].x);
1072 m_pathPointsOrg[i].y = (int)(64 * m_scaley * m_pathPointsOrg[i].y);
1073 if(minx > m_pathPointsOrg[i].x) minx = m_pathPointsOrg[i].x;
1074 if(miny > m_pathPointsOrg[i].y) miny = m_pathPointsOrg[i].y;
1075 if(maxx < m_pathPointsOrg[i].x) maxx = m_pathPointsOrg[i].x;
1076 if(maxy < m_pathPointsOrg[i].y) maxy = m_pathPointsOrg[i].y;
1078 m_width = max(maxx - minx, 0);
1079 m_ascent = max(maxy - miny, 0);
1080 int baseline = (int)(64 * m_scaley * m_baseline);
1081 m_descent = baseline;
1082 m_ascent -= baseline;
1083 m_width = ((int)(m_style.get().fontScaleX/100 * m_width) + 4) >> 3;
1084 m_ascent = ((int)(m_style.get().fontScaleY/100 * m_ascent) + 4) >> 3;
1085 m_descent = ((int)(m_style.get().fontScaleY/100 * m_descent) + 4) >> 3;
1086 return(true);
1089 bool CPolygon::CreatePath(const SharedPtrPathData& path_data)
1091 int len = m_pathTypesOrg.GetCount();
1092 if(len == 0) return(false);
1093 if(path_data->mPathPoints != len)
1095 path_data->mpPathTypes = (BYTE*)realloc(path_data->mpPathTypes, len*sizeof(BYTE));
1096 path_data->mpPathPoints = (POINT*)realloc(path_data->mpPathPoints, len*sizeof(POINT));
1097 if(!path_data->mpPathTypes || !path_data->mpPathPoints) return(false);
1098 path_data->mPathPoints = len;
1100 memcpy(path_data->mpPathTypes, m_pathTypesOrg.GetData(), len*sizeof(BYTE));
1101 memcpy(path_data->mpPathPoints, m_pathPointsOrg.GetData(), len*sizeof(POINT));
1102 return(true);
1105 // CClipper
1107 CClipper::CClipper(CStringW str, CSize size, double scalex, double scaley, bool inverse)
1108 : m_polygon( new CPolygon(FwSTSStyle(), str, 0, 0, 0, scalex, scaley, 0) )
1110 m_size.cx = m_size.cy = 0;
1111 //m_pAlphaMask = NULL;
1112 if(size.cx < 0 || size.cy < 0)
1113 return;
1114 m_pAlphaMask.reset(new BYTE[size.cx*size.cy]);
1115 if( !m_pAlphaMask )
1116 return;
1117 m_size = size;
1118 m_inverse = inverse;
1119 memset( m_pAlphaMask.get(), 0, size.cx*size.cy);
1120 OverlayList overlay_list;
1121 CWord::Paint( m_polygon, CPoint(0, 0), CPoint(0, 0), &overlay_list );
1122 int w = overlay_list.overlay->mOverlayWidth, h = overlay_list.overlay->mOverlayHeight;
1123 int x = (overlay_list.overlay->mOffsetX+4)>>3, y = (overlay_list.overlay->mOffsetY+4)>>3;
1124 int xo = 0, yo = 0;
1125 if(x < 0) {xo = -x; w -= -x; x = 0;}
1126 if(y < 0) {yo = -y; h -= -y; y = 0;}
1127 if(x+w > m_size.cx) w = m_size.cx-x;
1128 if(y+h > m_size.cy) h = m_size.cy-y;
1129 if(w <= 0 || h <= 0) return;
1130 const BYTE* src = overlay_list.overlay->mpOverlayBuffer.body + (overlay_list.overlay->mOverlayPitch * yo + xo);
1131 BYTE* dst = m_pAlphaMask.get() + m_size.cx * y + x;
1132 while(h--)
1134 //for(int wt=0; wt<w; ++wt)
1135 // dst[wt] = src[wt];
1136 memcpy(dst, src, w);
1137 src += overlay_list.overlay->mOverlayPitch;
1138 dst += m_size.cx;
1140 if(inverse)
1142 BYTE* dst = m_pAlphaMask.get();
1143 for(int i = size.cx*size.cy; i>0; --i, ++dst)
1144 *dst = 0x40 - *dst; // mask is 6 bit
1148 CClipper::~CClipper()
1150 m_pAlphaMask.reset(NULL);
1153 // CLine
1155 CLine::~CLine()
1157 //POSITION pos = GetHeadPosition();
1158 //while(pos) delete GetNext(pos);
1161 void CLine::Compact()
1163 POSITION pos = GetHeadPosition();
1164 while(pos)
1166 SharedPtrCWord w = GetNext(pos);
1167 if(!w->m_fWhiteSpaceChar) break;
1168 m_width -= w->m_width;
1169 // delete w;
1170 RemoveHead();
1172 pos = GetTailPosition();
1173 while(pos)
1175 SharedPtrCWord w = GetPrev(pos);
1176 if(!w->m_fWhiteSpaceChar) break;
1177 m_width -= w->m_width;
1178 // delete w;
1179 RemoveTail();
1181 if(IsEmpty()) return;
1182 CLine l;
1183 l.AddTailList(this);
1184 RemoveAll();
1185 SharedPtrCWord last;
1186 pos = l.GetHeadPosition();
1187 while(pos)
1189 SharedPtrCWord w = l.GetNext(pos);
1190 if(!last || !last->Append(w))
1191 AddTail(last = w->Copy());
1193 m_ascent = m_descent = m_borderX = m_borderY = 0;
1194 pos = GetHeadPosition();
1195 while(pos)
1197 SharedPtrCWord w = GetNext(pos);
1198 if(m_ascent < w->m_ascent) m_ascent = w->m_ascent;
1199 if(m_descent < w->m_descent) m_descent = w->m_descent;
1200 if(m_borderX < w->m_style.get().outlineWidthX) m_borderX = (int)(w->m_style.get().outlineWidthX+0.5);
1201 if(m_borderY < w->m_style.get().outlineWidthY) m_borderY = (int)(w->m_style.get().outlineWidthY+0.5);
1205 CRect CLine::PaintAll( CompositeDrawItemList* output, SubPicDesc& spd, const CRect& clipRect,
1206 SharedArrayByte pAlphaMask, CPoint p, const CPoint& org, const int time, const int alpha )
1208 CRect bbox(0, 0, 0, 0);
1209 POSITION pos = GetHeadPosition();
1210 POSITION outputPos = output->GetHeadPosition();
1211 while(pos)
1213 SharedPtrCWord w = GetNext(pos);
1214 CompositeDrawItem& outputItem = output->GetNext(outputPos);
1215 if(w->m_fLineBreak) return(bbox); // should not happen since this class is just a line of text without any breaks
1216 CPoint shadowPos, outlinePos, bodyPos;
1217 shadowPos.x = p.x + static_cast<int>(w->m_style.get().shadowDepthX+0.5);
1218 shadowPos.y = p.y + m_ascent - w->m_ascent + static_cast<int>(w->m_style.get().shadowDepthY+0.5);
1219 outlinePos = CPoint(p.x, p.y + m_ascent - w->m_ascent);
1220 bodyPos = CPoint(p.x, p.y + m_ascent - w->m_ascent);
1221 //shadow
1223 if(w->m_style.get().shadowDepthX != 0 || w->m_style.get().shadowDepthY != 0)
1225 DWORD a = 0xff - w->m_style.get().alpha[3];
1226 if(alpha > 0) a = MulDiv(a, 0xff - alpha, 0xff);
1227 COLORREF shadow = revcolor(w->m_style.get().colors[3]) | (a<<24);
1228 DWORD sw[6] = {shadow, -1};
1229 //xy
1230 if(spd.type == MSP_AUYV)
1232 sw[0] =rgb2yuv(sw[0], XY_AUYV);
1234 else if(spd.type == MSP_AYUV || spd.type == MSP_AY11)
1236 sw[0] =rgb2yuv(sw[0], XY_AYUV);
1238 OverlayList overlay_list;
1239 CWord::Paint(w, shadowPos, org-shadowPos, &overlay_list);
1240 if(w->m_style.get().borderStyle == 0)
1242 outputItem.shadow.reset(
1243 Rasterizer::CreateDrawItem(spd, overlay_list.overlay, clipRect, pAlphaMask, shadowPos.x, shadowPos.y, sw,
1244 w->m_ktype > 0 || w->m_style.get().alpha[0] < 0xff,
1245 (w->m_style.get().outlineWidthX+w->m_style.get().outlineWidthY > 0) && !(w->m_ktype == 2 && time < w->m_kstart))
1247 bbox |= Rasterizer::DryDraw(spd, *outputItem.shadow);
1249 else if(w->m_style.get().borderStyle == 1 && w->m_pOpaqueBox)
1251 outputItem.shadow.reset(
1252 Rasterizer::CreateDrawItem(spd, overlay_list.next->overlay, clipRect, pAlphaMask, shadowPos.x, shadowPos.y, sw, true, false)
1254 bbox |= Rasterizer::DryDraw(spd, *outputItem.shadow);
1258 //outline
1260 if(w->m_style.get().outlineWidthX+w->m_style.get().outlineWidthY > 0 && !(w->m_ktype == 2 && time < w->m_kstart))
1262 DWORD aoutline = w->m_style.get().alpha[2];
1263 if(alpha > 0) aoutline += MulDiv(alpha, 0xff - w->m_style.get().alpha[2], 0xff);
1264 COLORREF outline = revcolor(w->m_style.get().colors[2]) | ((0xff-aoutline)<<24);
1265 DWORD sw[6] = {outline, -1};
1266 //xy
1267 if(spd.type == MSP_AUYV)
1269 sw[0] =rgb2yuv(sw[0], XY_AUYV);
1271 else if(spd.type == MSP_AYUV || spd.type == MSP_AY11)
1273 sw[0] =rgb2yuv(sw[0], XY_AYUV);
1275 OverlayList overlay_list;
1276 CWord::Paint(w, outlinePos, org-outlinePos, &overlay_list);
1277 if(w->m_style.get().borderStyle == 0)
1279 outputItem.outline.reset(
1280 Rasterizer::CreateDrawItem(spd, overlay_list.overlay, clipRect, pAlphaMask, outlinePos.x, outlinePos.y, sw, !w->m_style.get().alpha[0] && !w->m_style.get().alpha[1] && !alpha, true)
1282 bbox |= Rasterizer::DryDraw(spd, *outputItem.outline);
1284 else if(w->m_style.get().borderStyle == 1 && w->m_pOpaqueBox)
1286 outputItem.outline.reset(
1287 Rasterizer::CreateDrawItem(spd, overlay_list.next->overlay, clipRect, pAlphaMask, outlinePos.x, outlinePos.y, sw, true, false)
1289 bbox |= Rasterizer::DryDraw(spd, *outputItem.outline);
1293 //body
1295 // colors
1296 DWORD aprimary = w->m_style.get().alpha[0];
1297 if(alpha > 0) aprimary += MulDiv(alpha, 0xff - w->m_style.get().alpha[0], 0xff);
1298 COLORREF primary = revcolor(w->m_style.get().colors[0]) | ((0xff-aprimary)<<24);
1299 DWORD asecondary = w->m_style.get().alpha[1];
1300 if(alpha > 0) asecondary += MulDiv(alpha, 0xff - w->m_style.get().alpha[1], 0xff);
1301 COLORREF secondary = revcolor(w->m_style.get().colors[1]) | ((0xff-asecondary)<<24);
1302 DWORD sw[6] = {primary, 0, secondary};
1303 // karaoke
1304 double t;
1305 if(w->m_ktype == 0 || w->m_ktype == 2)
1307 t = time < w->m_kstart ? 0 : 1;
1309 else if(w->m_ktype == 1)
1311 if(time < w->m_kstart) t = 0;
1312 else if(time < w->m_kend)
1314 t = 1.0 * (time - w->m_kstart) / (w->m_kend - w->m_kstart);
1315 double angle = fmod(w->m_style.get().fontAngleZ, 360.0);
1316 if(angle > 90 && angle < 270)
1318 t = 1-t;
1319 COLORREF tmp = sw[0];
1320 sw[0] = sw[2];
1321 sw[2] = tmp;
1324 else t = 1.0;
1326 if(t >= 1)
1328 sw[1] = 0xffffffff;
1330 sw[3] = (int)(w->m_style.get().outlineWidthX + t*w->m_width) >> 3;
1331 sw[4] = sw[2];
1332 sw[5] = 0x00ffffff;
1333 //xy
1334 if(spd.type == MSP_AUYV)
1336 sw[0] =rgb2yuv(sw[0], XY_AUYV);
1337 sw[2] =rgb2yuv(sw[2], XY_AUYV);
1338 sw[4] =rgb2yuv(sw[4], XY_AUYV);
1340 else if(spd.type == MSP_AYUV || spd.type == MSP_AY11)
1342 sw[0] =rgb2yuv(sw[0], XY_AYUV);
1343 sw[2] =rgb2yuv(sw[2], XY_AYUV);
1344 sw[4] =rgb2yuv(sw[4], XY_AYUV);
1346 OverlayList overlay_list;
1347 CWord::Paint(w, bodyPos, org-bodyPos, &overlay_list);
1348 outputItem.body.reset(
1349 Rasterizer::CreateDrawItem(spd, overlay_list.overlay, clipRect, pAlphaMask, bodyPos.x, bodyPos.y, sw, true, false)
1351 bbox |= Rasterizer::DryDraw(spd, *outputItem.body);
1353 p.x += w->m_width;
1355 return(bbox);
1358 void CLine::AddWord2Tail( SharedPtrCWord words )
1360 __super::AddTail(words);
1363 bool CLine::IsEmpty()
1365 return __super::IsEmpty();
1368 int CLine::GetWordCount()
1370 return GetCount();
1373 // CSubtitle
1375 CSubtitle::CSubtitle()
1377 memset(m_effects, 0, sizeof(Effect*)*EF_NUMBEROFEFFECTS);
1378 m_pClipper = NULL;
1379 m_clipInverse = false;
1380 m_scalex = m_scaley = 1;
1381 m_fAnimated2 = false;
1384 CSubtitle::~CSubtitle()
1386 Empty();
1389 void CSubtitle::Empty()
1391 POSITION pos = GetHeadPosition();
1392 while(pos) delete GetNext(pos);
1393 // pos = m_words.GetHeadPosition();
1394 // while(pos) delete m_words.GetNext(pos);
1395 for(int i = 0; i < EF_NUMBEROFEFFECTS; i++) {if(m_effects[i]) delete m_effects[i];}
1396 memset(m_effects, 0, sizeof(Effect*)*EF_NUMBEROFEFFECTS);
1397 if(m_pClipper) delete m_pClipper;
1398 m_pClipper = NULL;
1401 int CSubtitle::GetFullWidth()
1403 int width = 0;
1404 POSITION pos = m_words.GetHeadPosition();
1405 while(pos) width += m_words.GetNext(pos)->m_width;
1406 return(width);
1409 int CSubtitle::GetFullLineWidth(POSITION pos)
1411 int width = 0;
1412 while(pos)
1414 SharedPtrCWord w = m_words.GetNext(pos);
1415 if(w->m_fLineBreak) break;
1416 width += w->m_width;
1418 return(width);
1421 int CSubtitle::GetWrapWidth(POSITION pos, int maxwidth)
1423 if(m_wrapStyle == 0 || m_wrapStyle == 3)
1425 if(maxwidth > 0)
1427 // int fullwidth = GetFullWidth();
1428 int fullwidth = GetFullLineWidth(pos);
1429 int minwidth = fullwidth / ((abs(fullwidth) / maxwidth) + 1);
1430 int width = 0, wordwidth = 0;
1431 while(pos && width < minwidth)
1433 SharedPtrCWord w = m_words.GetNext(pos);
1434 wordwidth = w->m_width;
1435 if(abs(width + wordwidth) < abs(maxwidth)) width += wordwidth;
1437 maxwidth = width;
1438 if(m_wrapStyle == 3 && pos) maxwidth -= wordwidth;
1441 else if(m_wrapStyle == 1)
1443 // maxwidth = maxwidth;
1445 else if(m_wrapStyle == 2)
1447 maxwidth = INT_MAX;
1449 return(maxwidth);
1452 CLine* CSubtitle::GetNextLine(POSITION& pos, int maxwidth)
1454 if(pos == NULL) return(NULL);
1455 CLine* ret = new CLine();
1456 if(!ret) return(NULL);
1457 ret->m_width = ret->m_ascent = ret->m_descent = ret->m_borderX = ret->m_borderY = 0;
1458 maxwidth = GetWrapWidth(pos, maxwidth);
1459 bool fEmptyLine = true;
1460 while(pos)
1462 SharedPtrCWord w = m_words.GetNext(pos);
1463 if(ret->m_ascent < w->m_ascent) ret->m_ascent = w->m_ascent;
1464 if(ret->m_descent < w->m_descent) ret->m_descent = w->m_descent;
1465 if(ret->m_borderX < w->m_style.get().outlineWidthX) ret->m_borderX = (int)(w->m_style.get().outlineWidthX+0.5);
1466 if(ret->m_borderY < w->m_style.get().outlineWidthY) ret->m_borderY = (int)(w->m_style.get().outlineWidthY+0.5);
1467 if(w->m_fLineBreak)
1469 if(fEmptyLine) {ret->m_ascent /= 2; ret->m_descent /= 2; ret->m_borderX = ret->m_borderY = 0;}
1470 ret->Compact();
1471 return(ret);
1473 fEmptyLine = false;
1474 bool fWSC = w->m_fWhiteSpaceChar;
1475 int width = w->m_width;
1476 POSITION pos2 = pos;
1477 while(pos2)
1479 if(m_words.GetAt(pos2)->m_fWhiteSpaceChar != fWSC
1480 || m_words.GetAt(pos2)->m_fLineBreak) break;
1481 SharedPtrCWord w2 = m_words.GetNext(pos2);
1482 width += w2->m_width;
1484 if((ret->m_width += width) <= maxwidth || ret->IsEmpty())
1486 ret->AddWord2Tail(w);
1487 while(pos != pos2)
1489 ret->AddWord2Tail(m_words.GetNext(pos));
1491 pos = pos2;
1493 else
1495 if(pos) m_words.GetPrev(pos);
1496 else pos = m_words.GetTailPosition();
1497 ret->m_width -= width;
1498 break;
1501 ret->Compact();
1502 return(ret);
1505 void CSubtitle::CreateClippers(CSize size)
1507 size.cx >>= 3;
1508 size.cy >>= 3;
1509 if(m_effects[EF_BANNER] && m_effects[EF_BANNER]->param[2])
1511 int width = m_effects[EF_BANNER]->param[2];
1512 int w = size.cx, h = size.cy;
1513 if(!m_pClipper)
1515 CStringW str;
1516 str.Format(L"m %d %d l %d %d %d %d %d %d", 0, 0, w, 0, w, h, 0, h);
1517 m_pClipper = new CClipper(str, size, 1, 1, false);
1518 if(!m_pClipper) return;
1520 int da = (64<<8)/width;
1521 BYTE* am = m_pClipper->m_pAlphaMask.get();
1522 for(int j = 0; j < h; j++, am += w)
1524 int a = 0;
1525 int k = min(width, w);
1526 for(int i = 0; i < k; i++, a += da)
1527 am[i] = (am[i]*a)>>14;
1528 a = 0x40<<8;
1529 k = w-width;
1530 if(k < 0) {a -= -k*da; k = 0;}
1531 for(int i = k; i < w; i++, a -= da)
1532 am[i] = (am[i]*a)>>14;
1535 else if(m_effects[EF_SCROLL] && m_effects[EF_SCROLL]->param[4])
1537 int height = m_effects[EF_SCROLL]->param[4];
1538 int w = size.cx, h = size.cy;
1539 if(!m_pClipper)
1541 CStringW str;
1542 str.Format(L"m %d %d l %d %d %d %d %d %d", 0, 0, w, 0, w, h, 0, h);
1543 m_pClipper = new CClipper(str, size, 1, 1, false);
1544 if(!m_pClipper) return;
1546 int da = (64<<8)/height;
1547 int a = 0;
1548 int k = m_effects[EF_SCROLL]->param[0]>>3;
1549 int l = k+height;
1550 if(k < 0) {a += -k*da; k = 0;}
1551 if(l > h) {l = h;}
1552 if(k < h)
1554 BYTE* am = &m_pClipper->m_pAlphaMask[k*w];
1555 memset(m_pClipper->m_pAlphaMask.get(), 0, am - m_pClipper->m_pAlphaMask.get());
1556 for(int j = k; j < l; j++, a += da)
1558 for(int i = 0; i < w; i++, am++)
1559 *am = ((*am)*a)>>14;
1562 da = -(64<<8)/height;
1563 a = 0x40<<8;
1564 l = m_effects[EF_SCROLL]->param[1]>>3;
1565 k = l-height;
1566 if(k < 0) {a += -k*da; k = 0;}
1567 if(l > h) {l = h;}
1568 if(k < h)
1570 BYTE* am = &m_pClipper->m_pAlphaMask[k*w];
1571 int j = k;
1572 for(; j < l; j++, a += da)
1574 for(int i = 0; i < w; i++, am++)
1575 *am = ((*am)*a)>>14;
1577 memset(am, 0, (h-j)*w);
1582 void CSubtitle::MakeLines(CSize size, CRect marginRect)
1584 CSize spaceNeeded(0, 0);
1585 bool fFirstLine = true;
1586 m_topborder = m_bottomborder = 0;
1587 CLine* l = NULL;
1588 POSITION pos = m_words.GetHeadPosition();
1589 while(pos)
1591 l = GetNextLine(pos, size.cx - marginRect.left - marginRect.right);
1592 if(!l) break;
1593 if(fFirstLine) {m_topborder = l->m_borderY; fFirstLine = false;}
1594 spaceNeeded.cx = max(l->m_width+l->m_borderX, spaceNeeded.cx);
1595 spaceNeeded.cy += l->m_ascent + l->m_descent;
1596 AddTail(l);
1598 if(l) m_bottomborder = l->m_borderY;
1599 m_rect = CRect(
1600 CPoint((m_scrAlignment%3) == 1 ? marginRect.left
1601 : (m_scrAlignment%3) == 2 ? (marginRect.left + (size.cx - marginRect.right) - spaceNeeded.cx + 1) / 2
1602 : (size.cx - marginRect.right - spaceNeeded.cx),
1603 m_scrAlignment <= 3 ? (size.cy - marginRect.bottom - spaceNeeded.cy)
1604 : m_scrAlignment <= 6 ? (marginRect.top + (size.cy - marginRect.bottom) - spaceNeeded.cy + 1) / 2
1605 : marginRect.top),
1606 spaceNeeded);
1609 POSITION CSubtitle::GetHeadLinePosition()
1611 return __super::GetHeadPosition();
1614 CLine* CSubtitle::GetNextLine( POSITION& pos )
1616 return __super::GetNext(pos);
1619 // CScreenLayoutAllocator
1621 void CScreenLayoutAllocator::Empty()
1623 m_subrects.RemoveAll();
1626 void CScreenLayoutAllocator::AdvanceToSegment(int segment, const CAtlArray<int>& sa)
1628 POSITION pos = m_subrects.GetHeadPosition();
1629 while(pos)
1631 POSITION prev = pos;
1632 SubRect& sr = m_subrects.GetNext(pos);
1633 bool fFound = false;
1634 if(abs(sr.segment - segment) <= 1) // using abs() makes it possible to play the subs backwards, too :)
1636 for(size_t i = 0; i < sa.GetCount() && !fFound; i++)
1638 if(sa[i] == sr.entry)
1640 sr.segment = segment;
1641 fFound = true;
1645 if(!fFound) m_subrects.RemoveAt(prev);
1649 CRect CScreenLayoutAllocator::AllocRect(CSubtitle* s, int segment, int entry, int layer, int collisions)
1651 // TODO: handle collisions == 1 (reversed collisions)
1652 POSITION pos = m_subrects.GetHeadPosition();
1653 while(pos)
1655 SubRect& sr = m_subrects.GetNext(pos);
1656 if(sr.segment == segment && sr.entry == entry)
1658 return(sr.r + CRect(0, -s->m_topborder, 0, -s->m_bottomborder));
1661 CRect r = s->m_rect + CRect(0, s->m_topborder, 0, s->m_bottomborder);
1662 bool fSearchDown = s->m_scrAlignment > 3;
1663 bool fOK;
1666 fOK = true;
1667 pos = m_subrects.GetHeadPosition();
1668 while(pos)
1670 SubRect& sr = m_subrects.GetNext(pos);
1671 if(layer == sr.layer && !(r & sr.r).IsRectEmpty())
1673 if(fSearchDown)
1675 r.bottom = sr.r.bottom + r.Height();
1676 r.top = sr.r.bottom;
1678 else
1680 r.top = sr.r.top - r.Height();
1681 r.bottom = sr.r.top;
1683 fOK = false;
1687 while(!fOK);
1688 SubRect sr;
1689 sr.r = r;
1690 sr.segment = segment;
1691 sr.entry = entry;
1692 sr.layer = layer;
1693 m_subrects.AddTail(sr);
1694 return(sr.r + CRect(0, -s->m_topborder, 0, -s->m_bottomborder));
1697 // CRenderedTextSubtitle
1699 CAtlMap<CStringW, CRenderedTextSubtitle::AssCmdType, CStringElementTraits<CStringW>> CRenderedTextSubtitle::m_cmdMap;
1701 CRenderedTextSubtitle::CRenderedTextSubtitle(CCritSec* pLock)
1702 : CSubPicProviderImpl(pLock)
1704 if( m_cmdMap.IsEmpty() )
1706 InitCmdMap();
1708 m_size = CSize(0, 0);
1709 if(g_hDC_refcnt == 0)
1711 g_hDC = CreateCompatibleDC(NULL);
1712 SetBkMode(g_hDC, TRANSPARENT);
1713 SetTextColor(g_hDC, 0xffffff);
1714 SetMapMode(g_hDC, MM_TEXT);
1716 g_hDC_refcnt++;
1719 CRenderedTextSubtitle::~CRenderedTextSubtitle()
1721 Deinit();
1722 g_hDC_refcnt--;
1723 if(g_hDC_refcnt == 0) DeleteDC(g_hDC);
1726 void CRenderedTextSubtitle::InitCmdMap()
1728 if( m_cmdMap.IsEmpty() )
1730 m_cmdMap.SetAt(L"1c", CMD_1c);
1731 m_cmdMap.SetAt(L"2c", CMD_2c);
1732 m_cmdMap.SetAt(L"3c", CMD_3c);
1733 m_cmdMap.SetAt(L"4c", CMD_4c);
1734 m_cmdMap.SetAt(L"1a", CMD_1a);
1735 m_cmdMap.SetAt(L"2a", CMD_2a);
1736 m_cmdMap.SetAt(L"3a", CMD_3a);
1737 m_cmdMap.SetAt(L"4a", CMD_4a);
1738 m_cmdMap.SetAt(L"alpha", CMD_alpha);
1739 m_cmdMap.SetAt(L"an", CMD_an);
1740 m_cmdMap.SetAt(L"a", CMD_a);
1741 m_cmdMap.SetAt(L"blur", CMD_blur);
1742 m_cmdMap.SetAt(L"bord", CMD_bord);
1743 m_cmdMap.SetAt(L"be", CMD_be);
1744 m_cmdMap.SetAt(L"b", CMD_b);
1745 m_cmdMap.SetAt(L"clip", CMD_clip);
1746 m_cmdMap.SetAt(L"iclip", CMD_iclip);
1747 m_cmdMap.SetAt(L"c", CMD_c);
1748 m_cmdMap.SetAt(L"fade", CMD_fade);
1749 m_cmdMap.SetAt(L"fad", CMD_fad);
1750 m_cmdMap.SetAt(L"fax", CMD_fax);
1751 m_cmdMap.SetAt(L"fay", CMD_fay);
1752 m_cmdMap.SetAt(L"fe", CMD_fe);
1753 m_cmdMap.SetAt(L"fn", CMD_fn);
1754 m_cmdMap.SetAt(L"frx", CMD_frx);
1755 m_cmdMap.SetAt(L"fry", CMD_fry);
1756 m_cmdMap.SetAt(L"frz", CMD_frz);
1757 m_cmdMap.SetAt(L"fr", CMD_fr);
1758 m_cmdMap.SetAt(L"fscx", CMD_fscx);
1759 m_cmdMap.SetAt(L"fscy", CMD_fscy);
1760 m_cmdMap.SetAt(L"fsc", CMD_fsc);
1761 m_cmdMap.SetAt(L"fsp", CMD_fsp);
1762 m_cmdMap.SetAt(L"fs", CMD_fs);
1763 m_cmdMap.SetAt(L"i", CMD_i);
1764 m_cmdMap.SetAt(L"kt", CMD_kt);
1765 m_cmdMap.SetAt(L"kf", CMD_kf);
1766 m_cmdMap.SetAt(L"K", CMD_K);
1767 m_cmdMap.SetAt(L"ko", CMD_ko);
1768 m_cmdMap.SetAt(L"k", CMD_k);
1769 m_cmdMap.SetAt(L"move", CMD_move);
1770 m_cmdMap.SetAt(L"org", CMD_org);
1771 m_cmdMap.SetAt(L"pbo", CMD_pbo);
1772 m_cmdMap.SetAt(L"pos", CMD_pos);
1773 m_cmdMap.SetAt(L"p", CMD_p);
1774 m_cmdMap.SetAt(L"q", CMD_q);
1775 m_cmdMap.SetAt(L"r", CMD_r);
1776 m_cmdMap.SetAt(L"shad", CMD_shad);
1777 m_cmdMap.SetAt(L"s", CMD_s);
1778 m_cmdMap.SetAt(L"t", CMD_t);
1779 m_cmdMap.SetAt(L"u", CMD_u);
1780 m_cmdMap.SetAt(L"xbord", CMD_xbord);
1781 m_cmdMap.SetAt(L"xshad", CMD_xshad);
1782 m_cmdMap.SetAt(L"ybord", CMD_ybord);
1783 m_cmdMap.SetAt(L"yshad", CMD_yshad);
1787 void CRenderedTextSubtitle::Copy(CRenderedTextSubtitle& rts)
1789 __super::Copy(rts);
1790 m_size = rts.m_size;
1793 void CRenderedTextSubtitle::Copy(CSimpleTextSubtitle& sts)
1795 __super::Copy(sts);
1798 void CRenderedTextSubtitle::Empty()
1800 Deinit();
1801 __super::Empty();
1804 void CRenderedTextSubtitle::OnChanged()
1806 __super::OnChanged();
1807 POSITION pos = m_subtitleCache.GetStartPosition();
1808 while(pos)
1810 int i;
1811 CSubtitle* s;
1812 m_subtitleCache.GetNextAssoc(pos, i, s);
1813 delete s;
1815 m_subtitleCache.RemoveAll();
1816 m_sla.Empty();
1819 bool CRenderedTextSubtitle::Init(CSize size, CRect vidrect)
1821 Deinit();
1822 m_size = CSize(size.cx*8, size.cy*8);
1823 m_vidrect = CRect(vidrect.left*8, vidrect.top*8, vidrect.right*8, vidrect.bottom*8);
1824 m_sla.Empty();
1825 return(true);
1828 void CRenderedTextSubtitle::Deinit()
1830 POSITION pos = m_subtitleCache.GetStartPosition();
1831 while(pos)
1833 int i;
1834 CSubtitle* s;
1835 m_subtitleCache.GetNextAssoc(pos, i, s);
1836 delete s;
1838 m_subtitleCache.RemoveAll();
1839 m_sla.Empty();
1840 m_size = CSize(0, 0);
1841 m_vidrect.SetRectEmpty();
1843 CacheManager::GetCWordMruCache()->RemoveAll();
1844 CacheManager::GetPathDataMruCache()->RemoveAll();
1845 CacheManager::GetScanLineDataMruCache()->RemoveAll();
1846 CacheManager::GetOverlayNoBlurMruCache()->RemoveAll();
1847 CacheManager::GetOverlayMruCache()->RemoveAll();
1848 CacheManager::GetAssTagListMruCache()->RemoveAll();
1849 CacheManager::GetSubpixelVarianceCache()->RemoveAll();
1850 CacheManager::GetTextInfoCache()->RemoveAll();
1853 void CRenderedTextSubtitle::ParseEffect(CSubtitle* sub, const CStringW& str)
1855 CStringW::PCXSTR str_start = str.GetString();
1856 CStringW::PCXSTR str_end = str_start + str.GetLength();
1857 str_start = SkipWhiteSpaceLeft(str_start, str_end);
1859 if(!sub || *str_start==0)
1860 return;
1862 str_end = FastSkipWhiteSpaceRight(str_start, str_end);
1864 const WCHAR* s = FindChar(str_start, str_end, L';');
1865 if(*s==L';') {
1866 s++;
1869 const CStringW effect(str_start, s-str_start);
1870 if(!effect.CompareNoCase( L"Banner;" ) )
1872 int delay, lefttoright = 0, fadeawaywidth = 0;
1873 if(swscanf(s, L"%d;%d;%d", &delay, &lefttoright, &fadeawaywidth) < 1) return;
1874 Effect* e = new Effect;
1875 if(!e) return;
1876 sub->m_effects[e->type = EF_BANNER] = e;
1877 e->param[0] = (int)(max(1.0*delay/sub->m_scalex, 1));
1878 e->param[1] = lefttoright;
1879 e->param[2] = (int)(sub->m_scalex*fadeawaywidth);
1880 sub->m_wrapStyle = 2;
1882 else if(!effect.CompareNoCase(L"Scroll up;") || !effect.CompareNoCase(L"Scroll down;"))
1884 int top, bottom, delay, fadeawayheight = 0;
1885 if(swscanf(s, L"%d;%d;%d;%d", &top, &bottom, &delay, &fadeawayheight) < 3) return;
1886 if(top > bottom) {int tmp = top; top = bottom; bottom = tmp;}
1887 Effect* e = new Effect;
1888 if(!e) return;
1889 sub->m_effects[e->type = EF_SCROLL] = e;
1890 e->param[0] = (int)(sub->m_scaley*top*8);
1891 e->param[1] = (int)(sub->m_scaley*bottom*8);
1892 e->param[2] = (int)(max(1.0*delay/sub->m_scaley, 1));
1893 e->param[3] = (effect.GetLength() == 12);
1894 e->param[4] = (int)(sub->m_scaley*fadeawayheight);
1898 void CRenderedTextSubtitle::ParseString(CSubtitle* sub, CStringW str, const FwSTSStyle& style)
1900 if(!sub) return;
1901 str.Replace(L"\\N", L"\n");
1902 str.Replace(L"\\n", (sub->m_wrapStyle < 2 || sub->m_wrapStyle == 3) ? L" " : L"\n");
1903 str.Replace(L"\\h", L"\x00A0");
1904 for(int ite = 0, j = 0, len = str.GetLength(); j <= len; j++)
1906 WCHAR c = str[j];
1907 if(c != L'\n' && c != L' ' && c != L'\x00A0' && c != 0)
1908 continue;
1909 if(ite < j)
1911 if(PCWord tmp_ptr = new CText(style, str.Mid(ite, j-ite), m_ktype, m_kstart, m_kend))
1913 SharedPtrCWord w(tmp_ptr);
1914 sub->m_words.AddTail(w);
1916 else
1918 ///TODO: overflow handling
1920 m_kstart = m_kend;
1922 if(c == L'\n')
1924 if(PCWord tmp_ptr = new CText(style, CStringW(), m_ktype, m_kstart, m_kend))
1926 SharedPtrCWord w(tmp_ptr);
1927 sub->m_words.AddTail(w);
1929 else
1931 ///TODO: overflow handling
1933 m_kstart = m_kend;
1935 else if(c == L' ' || c == L'\x00A0')
1937 if(PCWord tmp_ptr = new CText(style, CStringW(c), m_ktype, m_kstart, m_kend))
1939 SharedPtrCWord w(tmp_ptr);
1940 sub->m_words.AddTail(w);
1942 else
1944 ///TODO: overflow handling
1946 m_kstart = m_kend;
1948 ite = j+1;
1950 return;
1953 void CRenderedTextSubtitle::ParsePolygon(CSubtitle* sub, const CStringW& str, const FwSTSStyle& style)
1955 if(!sub || !str.GetLength() || !m_nPolygon) return;
1957 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))
1959 SharedPtrCWord w(tmp_ptr);
1960 ///Todo: fix me
1961 //if( PCWord w_cache = m_wordCache.lookup(*w) )
1963 // sub->m_words.AddTail(w_cache);
1964 // delete w;
1966 //else
1968 sub->m_words.AddTail(w);
1970 m_kstart = m_kend;
1974 bool CRenderedTextSubtitle::ParseSSATag( AssTagList *assTags, const CStringW& str )
1976 if(!assTags) return(false);
1977 int nTags = 0, nUnrecognizedTags = 0;
1978 for(int i = 0, j; (j = str.Find(L'\\', i)) >= 0; i = j)
1980 POSITION pos = assTags->AddTail();
1981 AssTag& assTag = assTags->GetAt(pos);
1982 assTag.cmdType = CMD_COUNT;
1984 j++;
1985 CStringW::PCXSTR str_start = str.GetString() + j;
1986 CStringW::PCXSTR pc = str_start;
1987 while( iswspace(*pc) )
1989 pc++;
1991 j += pc-str_start;
1992 str_start = pc;
1993 while( *pc && *pc != L'(' && *pc != L'\\' )
1995 pc++;
1997 j += pc-str_start;
1998 if( pc-str_start>0 )
2000 while( iswspace(*--pc) );
2001 pc++;
2004 const CStringW cmd(str_start, pc-str_start);
2005 if(cmd.IsEmpty()) continue;
2007 CAtlArray<CStringW>& params = assTag.strParams;
2008 if(str[j] == L'(')
2010 j++;
2011 CStringW::PCXSTR str_start = str.GetString() + j;
2012 CStringW::PCXSTR pc = str_start;
2013 while( iswspace(*pc) )
2015 pc++;
2017 j += pc-str_start;
2018 str_start = pc;
2019 while( *pc && *pc != L')' )
2021 pc++;
2023 j += pc-str_start;
2024 if( pc-str_start>0 )
2026 while( iswspace(*--pc) );
2027 pc++;
2030 CStringW::PCXSTR param_start = str_start;
2031 CStringW::PCXSTR param_end = pc;
2032 while( param_start<param_end )
2034 param_start = SkipWhiteSpaceLeft(param_start, param_end);
2036 CStringW::PCXSTR newstart = FindChar(param_start, param_end, L',');
2037 CStringW::PCXSTR newend = FindChar(param_start, param_end, L'\\');
2038 if(newstart > param_start && newstart < newend)
2040 newstart = FastSkipWhiteSpaceRight(param_start, newstart);
2041 CStringW s(param_start, newstart - param_start);
2043 if(!s.IsEmpty()) params.Add(s);
2044 param_start = newstart + 1;
2046 else if(param_start<param_end)
2048 CStringW s(param_start, param_end - param_start);
2050 params.Add(s);
2051 param_start = param_end;
2056 AssCmdType cmd_type = CMD_COUNT;
2057 int cmd_length = min(MAX_CMD_LENGTH, cmd.GetLength());
2058 for( ;cmd_length>=MIN_CMD_LENGTH;cmd_length-- )
2060 if( m_cmdMap.Lookup(cmd.Left(cmd_length), cmd_type) )
2061 break;
2063 if(cmd_length<MIN_CMD_LENGTH)
2064 cmd_type = CMD_COUNT;
2065 switch( cmd_type )
2067 case CMD_fax:
2068 case CMD_fay:
2069 case CMD_fe:
2070 case CMD_fn:
2071 case CMD_frx:
2072 case CMD_fry:
2073 case CMD_frz:
2074 case CMD_fr:
2075 case CMD_fscx:
2076 case CMD_fscy:
2077 case CMD_fsc:
2078 case CMD_fsp:
2079 case CMD_fs:
2080 case CMD_i:
2081 case CMD_kt:
2082 case CMD_kf:
2083 case CMD_K:
2084 case CMD_ko:
2085 case CMD_k:
2086 case CMD_pbo:
2087 case CMD_p:
2088 case CMD_q:
2089 case CMD_r:
2090 case CMD_shad:
2091 case CMD_s:
2092 case CMD_an:
2093 case CMD_a:
2094 case CMD_blur:
2095 case CMD_bord:
2096 case CMD_be:
2097 case CMD_b:
2098 case CMD_u:
2099 case CMD_xbord:
2100 case CMD_xshad:
2101 case CMD_ybord:
2102 case CMD_yshad:
2103 // default:
2104 params.Add(cmd.Mid(cmd_length));
2105 break;
2106 case CMD_c:
2107 case CMD_1c :
2108 case CMD_2c :
2109 case CMD_3c :
2110 case CMD_4c :
2111 case CMD_1a :
2112 case CMD_2a :
2113 case CMD_3a :
2114 case CMD_4a :
2115 case CMD_alpha:
2116 params.Add(cmd.Mid(cmd_length).Trim(L"&H"));
2117 break;
2118 case CMD_clip:
2119 case CMD_iclip:
2120 case CMD_fade:
2121 case CMD_fad:
2122 case CMD_move:
2123 case CMD_org:
2124 case CMD_pos:
2125 break;
2126 case CMD_t:
2127 ParseSSATag(&assTag.embeded, params[params.GetCount()-1]);
2128 break;
2129 case CMD_COUNT:
2130 nUnrecognizedTags++;
2131 break;
2134 assTag.cmd = cmd;
2135 assTag.cmdType = cmd_type;
2137 nTags++;
2139 return(true);
2142 bool CRenderedTextSubtitle::ParseSSATag( CSubtitle* sub, const AssTagList& assTags, STSStyle& style, const STSStyle& org, bool fAnimate /*= false*/ )
2144 if(!sub) return(false);
2146 POSITION pos = assTags.GetHeadPosition();
2147 while(pos)
2149 const AssTag& assTag = assTags.GetNext(pos);
2150 const CStringW& cmd = assTag.cmd;
2151 AssCmdType cmd_type = assTag.cmdType;
2152 const CAtlArray<CStringW>& params = assTag.strParams;
2154 // TODO: call ParseStyleModifier(cmd, params, ..) and move the rest there
2155 const CStringW& p = params.GetCount() > 0 ? params[0] : CStringW("");
2156 switch ( cmd_type )
2158 case CMD_1c :
2159 case CMD_2c :
2160 case CMD_3c :
2161 case CMD_4c :
2163 int i = cmd[0] - L'1';
2164 DWORD c = wcstol(p, NULL, 16);
2165 style.colors[i] = !p.IsEmpty()
2166 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2167 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2168 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2169 : org.colors[i];
2170 break;
2172 case CMD_1a :
2173 case CMD_2a :
2174 case CMD_3a :
2175 case CMD_4a :
2177 int i = cmd[0] - L'1';
2178 style.alpha[i] = !p.IsEmpty()
2179 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2180 : org.alpha[i];
2181 break;
2183 case CMD_alpha:
2185 for(int i = 0; i < 4; i++)
2187 style.alpha[i] = !p.IsEmpty()
2188 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2189 : org.alpha[i];
2191 break;
2193 case CMD_an:
2195 int n = wcstol(p, NULL, 10);
2196 if(sub->m_scrAlignment < 0)
2197 sub->m_scrAlignment = (n > 0 && n < 10) ? n : org.scrAlignment;
2198 break;
2200 case CMD_a:
2202 int n = wcstol(p, NULL, 10);
2203 if(sub->m_scrAlignment < 0)
2204 sub->m_scrAlignment = (n > 0 && n < 12) ? ((((n-1)&3)+1)+((n&4)?6:0)+((n&8)?3:0)) : org.scrAlignment;
2205 break;
2207 case CMD_blur:
2209 double n = CalcAnimation(wcstod(p, NULL), style.fGaussianBlur, fAnimate);
2210 style.fGaussianBlur = !p.IsEmpty()
2211 ? (n < 0 ? 0 : n)
2212 : org.fGaussianBlur;
2213 break;
2215 case CMD_bord:
2217 double dst = wcstod(p, NULL);
2218 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2219 style.outlineWidthX = !p.IsEmpty()
2220 ? (nx < 0 ? 0 : nx)
2221 : org.outlineWidthX;
2222 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2223 style.outlineWidthY = !p.IsEmpty()
2224 ? (ny < 0 ? 0 : ny)
2225 : org.outlineWidthY;
2226 break;
2228 case CMD_be:
2230 int n = (int)(CalcAnimation(wcstol(p, NULL, 10), style.fBlur, fAnimate)+0.5);
2231 style.fBlur = !p.IsEmpty()
2233 : org.fBlur;
2234 break;
2236 case CMD_b:
2238 int n = wcstol(p, NULL, 10);
2239 style.fontWeight = !p.IsEmpty()
2240 ? (n == 0 ? FW_NORMAL : n == 1 ? FW_BOLD : n >= 100 ? n : org.fontWeight)
2241 : org.fontWeight;
2242 break;
2244 case CMD_clip:
2245 case CMD_iclip:
2247 bool invert = (cmd_type == CMD_iclip);
2248 if(params.GetCount() == 1 && !sub->m_pClipper)
2250 sub->m_pClipper = new CClipper(params[0], CSize(m_size.cx>>3, m_size.cy>>3), sub->m_scalex, sub->m_scaley, invert);
2252 else if(params.GetCount() == 2 && !sub->m_pClipper)
2254 int scale = max(wcstol(p, NULL, 10), 1);
2255 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);
2257 else if(params.GetCount() == 4)
2259 CRect r;
2260 sub->m_clipInverse = invert;
2261 r.SetRect(
2262 wcstol(params[0], NULL, 10),
2263 wcstol(params[1], NULL, 10),
2264 wcstol(params[2], NULL, 10),
2265 wcstol(params[3], NULL, 10));
2266 CPoint o(0, 0);
2267 if(sub->m_relativeTo == 1) // TODO: this should also apply to the other two clippings above
2269 o.x = m_vidrect.left>>3;
2270 o.y = m_vidrect.top>>3;
2272 sub->m_clip.SetRect(
2273 (int)CalcAnimation(sub->m_scalex*r.left + o.x, sub->m_clip.left, fAnimate),
2274 (int)CalcAnimation(sub->m_scaley*r.top + o.y, sub->m_clip.top, fAnimate),
2275 (int)CalcAnimation(sub->m_scalex*r.right + o.x, sub->m_clip.right, fAnimate),
2276 (int)CalcAnimation(sub->m_scaley*r.bottom + o.y, sub->m_clip.bottom, fAnimate));
2278 break;
2280 case CMD_c:
2282 DWORD c = wcstol(p, NULL, 16);
2283 style.colors[0] = !p.IsEmpty()
2284 ? (((int)CalcAnimation(c&0xff, style.colors[0]&0xff, fAnimate))&0xff
2285 |((int)CalcAnimation(c&0xff00, style.colors[0]&0xff00, fAnimate))&0xff00
2286 |((int)CalcAnimation(c&0xff0000, style.colors[0]&0xff0000, fAnimate))&0xff0000)
2287 : org.colors[0];
2288 break;
2290 case CMD_fade:
2291 case CMD_fad:
2293 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])
2295 if(Effect* e = new Effect)
2297 for(int i = 0; i < 3; i++)
2298 e->param[i] = wcstol(params[i], NULL, 10);
2299 for(int i = 0; i < 4; i++)
2300 e->t[i] = wcstol(params[3+i], NULL, 10);
2301 sub->m_effects[EF_FADE] = e;
2304 else if(params.GetCount() == 2 && !sub->m_effects[EF_FADE]) // {\fad(t1=t[1], t2=t[2])
2306 if(Effect* e = new Effect)
2308 e->param[0] = e->param[2] = 0xff;
2309 e->param[1] = 0x00;
2310 for(int i = 1; i < 3; i++)
2311 e->t[i] = wcstol(params[i-1], NULL, 10);
2312 e->t[0] = e->t[3] = -1; // will be substituted with "start" and "end"
2313 sub->m_effects[EF_FADE] = e;
2316 break;
2318 case CMD_fax:
2320 style.fontShiftX = !p.IsEmpty()
2321 ? CalcAnimation(wcstod(p, NULL), style.fontShiftX, fAnimate)
2322 : org.fontShiftX;
2323 break;
2325 case CMD_fay:
2327 style.fontShiftY = !p.IsEmpty()
2328 ? CalcAnimation(wcstod(p, NULL), style.fontShiftY, fAnimate)
2329 : org.fontShiftY;
2330 break;
2332 case CMD_fe:
2334 int n = wcstol(p, NULL, 10);
2335 style.charSet = !p.IsEmpty()
2337 : org.charSet;
2338 break;
2340 case CMD_fn:
2342 if(!p.IsEmpty() && p != L'0')
2343 style.fontName = CString(p).Trim();
2344 else
2345 style.fontName = org.fontName;
2346 break;
2348 case CMD_frx:
2350 style.fontAngleX = !p.IsEmpty()
2351 ? CalcAnimation(wcstod(p, NULL), style.fontAngleX, fAnimate)
2352 : org.fontAngleX;
2353 break;
2355 case CMD_fry:
2357 style.fontAngleY = !p.IsEmpty()
2358 ? CalcAnimation(wcstod(p, NULL), style.fontAngleY, fAnimate)
2359 : org.fontAngleY;
2360 break;
2362 case CMD_frz:
2363 case CMD_fr:
2365 style.fontAngleZ = !p.IsEmpty()
2366 ? CalcAnimation(wcstod(p, NULL), style.fontAngleZ, fAnimate)
2367 : org.fontAngleZ;
2368 break;
2370 case CMD_fscx:
2372 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontScaleX, fAnimate);
2373 style.fontScaleX = !p.IsEmpty()
2374 ? ((n < 0) ? 0 : n)
2375 : org.fontScaleX;
2376 break;
2378 case CMD_fscy:
2380 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontScaleY, fAnimate);
2381 style.fontScaleY = !p.IsEmpty()
2382 ? ((n < 0) ? 0 : n)
2383 : org.fontScaleY;
2384 break;
2386 case CMD_fsc:
2388 style.fontScaleX = org.fontScaleX;
2389 style.fontScaleY = org.fontScaleY;
2390 break;
2392 case CMD_fsp:
2394 style.fontSpacing = !p.IsEmpty()
2395 ? CalcAnimation(wcstod(p, NULL), style.fontSpacing, fAnimate)
2396 : org.fontSpacing;
2397 break;
2399 case CMD_fs:
2401 if(!p.IsEmpty())
2403 if(p[0] == L'-' || p[0] == L'+')
2405 double n = CalcAnimation(style.fontSize + style.fontSize*wcstol(p, NULL, 10)/10, style.fontSize, fAnimate);
2406 style.fontSize = (n > 0) ? n : org.fontSize;
2408 else
2410 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontSize, fAnimate);
2411 style.fontSize = (n > 0) ? n : org.fontSize;
2414 else
2416 style.fontSize = org.fontSize;
2418 break;
2420 case CMD_i:
2422 int n = wcstol(p, NULL, 10);
2423 style.fItalic = !p.IsEmpty()
2424 ? (n == 0 ? false : n == 1 ? true : org.fItalic)
2425 : org.fItalic;
2426 break;
2428 case CMD_kt:
2430 m_kstart = !p.IsEmpty()
2431 ? wcstol(p, NULL, 10)*10
2432 : 0;
2433 m_kend = m_kstart;
2434 break;
2435 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2437 case CMD_kf:
2438 case CMD_K:
2440 m_ktype = 1;
2441 m_kstart = m_kend;
2442 m_kend += !p.IsEmpty()
2443 ? wcstol(p, NULL, 10)*10
2444 : 1000;
2445 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2446 break;
2448 case CMD_ko:
2450 m_ktype = 2;
2451 m_kstart = m_kend;
2452 m_kend += !p.IsEmpty()
2453 ? wcstol(p, NULL, 10)*10
2454 : 1000;
2455 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2456 break;
2458 case CMD_k:
2460 m_ktype = 0;
2461 m_kstart = m_kend;
2462 m_kend += !p.IsEmpty()
2463 ? wcstol(p, NULL, 10)*10
2464 : 1000;
2465 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2466 break;
2468 case CMD_move: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3][, t1=t[0], t2=t[1]])}
2470 if((params.GetCount() == 4 || params.GetCount() == 6) && !sub->m_effects[EF_MOVE])
2472 if(Effect* e = new Effect)
2474 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2475 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2476 e->param[2] = (int)(sub->m_scalex*wcstod(params[2], NULL)*8);
2477 e->param[3] = (int)(sub->m_scaley*wcstod(params[3], NULL)*8);
2478 e->t[0] = e->t[1] = -1;
2479 if(params.GetCount() == 6)
2481 for(int i = 0; i < 2; i++)
2482 e->t[i] = wcstol(params[4+i], NULL, 10);
2484 sub->m_effects[EF_MOVE] = e;
2487 break;
2489 case CMD_org: // {\org(x=param[0], y=param[1])}
2491 if(params.GetCount() == 2 && !sub->m_effects[EF_ORG])
2493 if(Effect* e = new Effect)
2495 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2496 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2497 sub->m_effects[EF_ORG] = e;
2500 break;
2502 case CMD_pbo:
2504 m_polygonBaselineOffset = wcstol(p, NULL, 10);
2505 break;
2507 case CMD_pos:
2509 if(params.GetCount() == 2 && !sub->m_effects[EF_MOVE])
2511 if(Effect* e = new Effect)
2513 e->param[0] = e->param[2] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2514 e->param[1] = e->param[3] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2515 e->t[0] = e->t[1] = 0;
2516 sub->m_effects[EF_MOVE] = e;
2519 break;
2521 case CMD_p:
2523 int n = wcstol(p, NULL, 10);
2524 m_nPolygon = (n <= 0 ? 0 : n);
2525 break;
2527 case CMD_q:
2529 int n = wcstol(p, NULL, 10);
2530 sub->m_wrapStyle = !p.IsEmpty() && (0 <= n && n <= 3)
2532 : m_defaultWrapStyle;
2533 break;
2535 case CMD_r:
2537 STSStyle* val;
2538 style = (!p.IsEmpty() && m_styles.Lookup(WToT(p), val) && val) ? *val : org;
2539 break;
2541 case CMD_shad:
2543 double dst = wcstod(p, NULL);
2544 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2545 style.shadowDepthX = !p.IsEmpty()
2546 ? (nx < 0 ? 0 : nx)
2547 : org.shadowDepthX;
2548 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2549 style.shadowDepthY = !p.IsEmpty()
2550 ? (ny < 0 ? 0 : ny)
2551 : org.shadowDepthY;
2552 break;
2554 case CMD_s:
2556 int n = wcstol(p, NULL, 10);
2557 style.fStrikeOut = !p.IsEmpty()
2558 ? (n == 0 ? false : n == 1 ? true : org.fStrikeOut)
2559 : org.fStrikeOut;
2560 break;
2562 case CMD_t: // \t([<t1>,<t2>,][<accel>,]<style modifiers>)
2564 CStringW param;
2565 m_animStart = m_animEnd = 0;
2566 m_animAccel = 1;
2567 if(params.GetCount() == 1)
2569 param = params[0];
2571 else if(params.GetCount() == 2)
2573 m_animAccel = wcstod(params[0], NULL);
2574 param = params[1];
2576 else if(params.GetCount() == 3)
2578 m_animStart = (int)wcstod(params[0], NULL);
2579 m_animEnd = (int)wcstod(params[1], NULL);
2580 param = params[2];
2582 else if(params.GetCount() == 4)
2584 m_animStart = wcstol(params[0], NULL, 10);
2585 m_animEnd = wcstol(params[1], NULL, 10);
2586 m_animAccel = wcstod(params[2], NULL);
2587 param = params[3];
2589 ParseSSATag(sub, assTag.embeded, style, org, true);
2590 sub->m_fAnimated = true;
2591 break;
2593 case CMD_u:
2595 int n = wcstol(p, NULL, 10);
2596 style.fUnderline = !p.IsEmpty()
2597 ? (n == 0 ? false : n == 1 ? true : org.fUnderline)
2598 : org.fUnderline;
2599 break;
2601 case CMD_xbord:
2603 double dst = wcstod(p, NULL);
2604 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2605 style.outlineWidthX = !p.IsEmpty()
2606 ? (nx < 0 ? 0 : nx)
2607 : org.outlineWidthX;
2608 break;
2610 case CMD_xshad:
2612 double dst = wcstod(p, NULL);
2613 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2614 style.shadowDepthX = !p.IsEmpty()
2615 ? nx
2616 : org.shadowDepthX;
2617 break;
2619 case CMD_ybord:
2621 double dst = wcstod(p, NULL);
2622 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2623 style.outlineWidthY = !p.IsEmpty()
2624 ? (ny < 0 ? 0 : ny)
2625 : org.outlineWidthY;
2626 break;
2628 case CMD_yshad:
2630 double dst = wcstod(p, NULL);
2631 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2632 style.shadowDepthY = !p.IsEmpty()
2633 ? ny
2634 : org.shadowDepthY;
2635 break;
2637 default:
2638 break;
2641 return(true);
2644 bool CRenderedTextSubtitle::ParseSSATag(CSubtitle* sub, const CStringW& str, STSStyle& style, const STSStyle& org, bool fAnimate)
2646 if(!sub) return(false);
2648 SharedPtrConstAssTagList assTags;
2649 AssTagListMruCache *ass_tag_cache = CacheManager::GetAssTagListMruCache();
2650 POSITION pos = ass_tag_cache->Lookup(str);
2651 if (pos==NULL)
2653 AssTagList *tmp = new AssTagList();
2654 ParseSSATag(tmp, str);
2655 assTags.reset(tmp);
2656 ass_tag_cache->UpdateCache(str, assTags);
2658 else
2660 assTags = ass_tag_cache->GetAt(pos);
2661 ass_tag_cache->UpdateCache( pos );
2663 return ParseSSATag(sub, *assTags, style, org, fAnimate);
2666 bool CRenderedTextSubtitle::ParseHtmlTag(CSubtitle* sub, CStringW str, STSStyle& style, STSStyle& org)
2668 if(str.Find(L"!--") == 0)
2669 return(true);
2670 bool fClosing = str[0] == L'/';
2671 str.Trim(L" /");
2672 int i = str.Find(L' ');
2673 if(i < 0) i = str.GetLength();
2674 CStringW tag = str.Left(i).MakeLower();
2675 str = str.Mid(i).Trim();
2676 CAtlArray<CStringW> attribs, params;
2677 while((i = str.Find(L'=')) > 0)
2679 attribs.Add(str.Left(i).Trim().MakeLower());
2680 str = str.Mid(i+1);
2681 for(i = 0; _istspace(str[i]); i++);
2682 str = str.Mid(i);
2683 if(str[0] == L'\"') {str = str.Mid(1); i = str.Find(L'\"');}
2684 else i = str.Find(L' ');
2685 if(i < 0) i = str.GetLength();
2686 params.Add(str.Left(i).Trim().MakeLower());
2687 str = str.Mid(i+1);
2689 if(tag == L"text")
2691 else if(tag == L"b" || tag == L"strong")
2692 style.fontWeight = !fClosing ? FW_BOLD : org.fontWeight;
2693 else if(tag == L"i" || tag == L"em")
2694 style.fItalic = !fClosing ? true : org.fItalic;
2695 else if(tag == L"u")
2696 style.fUnderline = !fClosing ? true : org.fUnderline;
2697 else if(tag == L"s" || tag == L"strike" || tag == L"del")
2698 style.fStrikeOut = !fClosing ? true : org.fStrikeOut;
2699 else if(tag == L"font")
2701 if(!fClosing)
2703 for(size_t i = 0; i < attribs.GetCount(); i++)
2705 if(params[i].IsEmpty()) continue;
2706 int nColor = -1;
2707 if(attribs[i] == L"face")
2709 style.fontName = params[i];
2711 else if(attribs[i] == L"size")
2713 if(params[i][0] == L'+')
2714 style.fontSize += wcstol(params[i], NULL, 10);
2715 else if(params[i][0] == L'-')
2716 style.fontSize -= wcstol(params[i], NULL, 10);
2717 else
2718 style.fontSize = wcstol(params[i], NULL, 10);
2720 else if(attribs[i] == L"color")
2722 nColor = 0;
2724 else if(attribs[i] == L"outline-color")
2726 nColor = 2;
2728 else if(attribs[i] == L"outline-level")
2730 style.outlineWidthX = style.outlineWidthY = wcstol(params[i], NULL, 10);
2732 else if(attribs[i] == L"shadow-color")
2734 nColor = 3;
2736 else if(attribs[i] == L"shadow-level")
2738 style.shadowDepthX = style.shadowDepthY = wcstol(params[i], NULL, 10);
2740 if(nColor >= 0 && nColor < 4)
2742 CString key = WToT(params[i]).TrimLeft(L'#');
2743 DWORD val;
2744 if(g_colors.Lookup(key, val))
2745 style.colors[nColor] = val;
2746 else if((style.colors[nColor] = _tcstol(key, NULL, 16)) == 0)
2747 style.colors[nColor] = 0x00ffffff; // default is white
2748 style.colors[nColor] = ((style.colors[nColor]>>16)&0xff)|((style.colors[nColor]&0xff)<<16)|(style.colors[nColor]&0x00ff00);
2752 else
2754 style.fontName = org.fontName;
2755 style.fontSize = org.fontSize;
2756 memcpy(style.colors, org.colors, sizeof(style.colors));
2759 else if(tag == L"k" && attribs.GetCount() == 1 && attribs[0] == L"t")
2761 m_ktype = 1;
2762 m_kstart = m_kend;
2763 m_kend += wcstol(params[0], NULL, 10);
2765 else
2766 return(false);
2767 return(true);
2770 double CRenderedTextSubtitle::CalcAnimation(double dst, double src, bool fAnimate)
2772 int s = m_animStart ? m_animStart : 0;
2773 int e = m_animEnd ? m_animEnd : m_delay;
2774 if(fabs(dst-src) >= 0.0001 && fAnimate)
2776 if(m_time < s) dst = src;
2777 else if(s <= m_time && m_time < e)
2779 double t = pow(1.0 * (m_time - s) / (e - s), m_animAccel);
2780 dst = (1 - t) * src + t * dst;
2782 // else dst = dst;
2784 return(dst);
2787 CSubtitle* CRenderedTextSubtitle::GetSubtitle(int entry)
2789 CSubtitle* sub;
2790 if(m_subtitleCache.Lookup(entry, sub))
2792 if(sub->m_fAnimated) {delete sub; sub = NULL;}
2793 else return(sub);
2795 sub = new CSubtitle();
2796 if(!sub) return(NULL);
2797 CStringW str = GetStrW(entry, true);
2798 STSStyle stss, orgstss;
2799 GetStyle(entry, &stss);
2800 if (stss.fontScaleX == stss.fontScaleY && m_dPARCompensation != 1.0)
2802 switch(m_ePARCompensationType)
2804 case EPCTUpscale:
2805 if (m_dPARCompensation < 1.0)
2806 stss.fontScaleY /= m_dPARCompensation;
2807 else
2808 stss.fontScaleX *= m_dPARCompensation;
2809 break;
2810 case EPCTDownscale:
2811 if (m_dPARCompensation < 1.0)
2812 stss.fontScaleX *= m_dPARCompensation;
2813 else
2814 stss.fontScaleY /= m_dPARCompensation;
2815 break;
2816 case EPCTAccurateSize:
2817 stss.fontScaleX *= m_dPARCompensation;
2818 break;
2821 orgstss = stss;
2822 sub->m_clip.SetRect(0, 0, m_size.cx>>3, m_size.cy>>3);
2823 sub->m_scrAlignment = -stss.scrAlignment;
2824 sub->m_wrapStyle = m_defaultWrapStyle;
2825 sub->m_fAnimated = false;
2826 sub->m_relativeTo = stss.relativeTo;
2827 sub->m_scalex = m_dstScreenSize.cx > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Width() : m_size.cx) / (m_dstScreenSize.cx*8) : 1.0;
2828 sub->m_scaley = m_dstScreenSize.cy > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Height() : m_size.cy) / (m_dstScreenSize.cy*8) : 1.0;
2829 m_animStart = m_animEnd = 0;
2830 m_animAccel = 1;
2831 m_ktype = m_kstart = m_kend = 0;
2832 m_nPolygon = 0;
2833 m_polygonBaselineOffset = 0;
2834 ParseEffect(sub, m_entries.GetAt(entry).effect);
2835 while(!str.IsEmpty())
2837 bool fParsed = false;
2838 int i;
2839 if(str[0] == L'{' && (i = str.Find(L'}')) > 0)
2841 if(fParsed = ParseSSATag(sub, str.Mid(1, i-1), stss, orgstss))
2842 str = str.Mid(i+1);
2844 else if(str[0] == L'<' && (i = str.Find(L'>')) > 0)
2846 if(fParsed = ParseHtmlTag(sub, str.Mid(1, i-1), stss, orgstss))
2847 str = str.Mid(i+1);
2849 if(fParsed)
2851 i = str.FindOneOf(L"{<");
2852 if(i < 0) i = str.GetLength();
2853 if(i == 0) continue;
2855 else
2857 i = str.Mid(1).FindOneOf(L"{<");
2858 if(i < 0) i = str.GetLength()-1;
2859 i++;
2861 STSStyle tmp = stss;
2862 tmp.fontSize = sub->m_scaley*tmp.fontSize*64;
2863 tmp.fontSpacing = sub->m_scalex*tmp.fontSpacing*64;
2864 tmp.outlineWidthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2865 tmp.outlineWidthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2866 tmp.shadowDepthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2867 tmp.shadowDepthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2868 FwSTSStyle fw_tmp(tmp);
2869 if(m_nPolygon)
2871 ParsePolygon(sub, str.Left(i), fw_tmp);
2873 else
2875 ParseString(sub, str.Left(i), fw_tmp);
2877 str = str.Mid(i);
2879 sub->m_fAnimated2 |= sub->m_fAnimated;
2880 if( sub->m_effects[EF_FADE] || sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL]
2881 || sub->m_effects[EF_MOVE] )
2882 sub->m_fAnimated2 = true;
2883 // just a "work-around" solution... in most cases nobody will want to use \org together with moving but without rotating the subs
2884 if(sub->m_effects[EF_ORG] && (sub->m_effects[EF_MOVE] || sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL]))
2885 sub->m_fAnimated = true;
2886 sub->m_scrAlignment = abs(sub->m_scrAlignment);
2887 STSEntry stse = m_entries.GetAt(entry);
2888 CRect marginRect = stse.marginRect;
2889 if(marginRect.left == 0) marginRect.left = orgstss.marginRect.get().left;
2890 if(marginRect.top == 0) marginRect.top = orgstss.marginRect.get().top;
2891 if(marginRect.right == 0) marginRect.right = orgstss.marginRect.get().right;
2892 if(marginRect.bottom == 0) marginRect.bottom = orgstss.marginRect.get().bottom;
2893 marginRect.left = (int)(sub->m_scalex*marginRect.left*8);
2894 marginRect.top = (int)(sub->m_scaley*marginRect.top*8);
2895 marginRect.right = (int)(sub->m_scalex*marginRect.right*8);
2896 marginRect.bottom = (int)(sub->m_scaley*marginRect.bottom*8);
2897 if(stss.relativeTo == 1)
2899 marginRect.left += m_vidrect.left;
2900 marginRect.top += m_vidrect.top;
2901 marginRect.right += m_size.cx - m_vidrect.right;
2902 marginRect.bottom += m_size.cy - m_vidrect.bottom;
2904 sub->CreateClippers(m_size);
2905 sub->MakeLines(m_size, marginRect);
2906 m_subtitleCache[entry] = sub;
2907 return(sub);
2912 STDMETHODIMP CRenderedTextSubtitle::NonDelegatingQueryInterface(REFIID riid, void** ppv)
2914 CheckPointer(ppv, E_POINTER);
2915 *ppv = NULL;
2916 return
2917 QI(IPersist)
2918 QI(ISubStream)
2919 QI(ISubPicProvider)
2920 QI(ISubPicProviderEx)
2921 __super::NonDelegatingQueryInterface(riid, ppv);
2924 // ISubPicProvider
2926 STDMETHODIMP_(POSITION) CRenderedTextSubtitle::GetStartPosition(REFERENCE_TIME rt, double fps)
2928 //DbgLog((LOG_TRACE, 3, "rt:%lu", (ULONG)rt/10000));
2929 m_fps = fps;//fix me: check is fps changed and do some re-init thing
2930 int iSegment;
2931 int subIndex = 1;//If a segment has animate effect then it corresponds to several subpics.
2932 //subIndex, 1 based, indicates which subpic the result corresponds to.
2933 rt /= 10000i64;
2934 const STSSegment *stss = SearchSubs((int)rt, fps, &iSegment, NULL);
2935 if(stss==NULL)
2936 return NULL;
2937 else if(stss->animated)
2939 int start = TranslateSegmentStart(iSegment, fps);
2940 if(rt > start)
2941 subIndex = (rt-start)/RTS_ANIMATE_SUBPIC_DUR + 1;
2943 //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));
2944 return (POSITION)(subIndex | (iSegment<<RTS_POS_SEGMENT_INDEX_BITS));
2945 //if(iSegment < 0) iSegment = 0;
2946 //return(GetNext((POSITION)iSegment));
2949 STDMETHODIMP_(POSITION) CRenderedTextSubtitle::GetNext(POSITION pos)
2951 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2952 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2953 const STSSegment *stss = GetSegment(iSegment);
2954 ASSERT(stss!=NULL && stss->subs.GetCount()>0);
2955 //DbgLog((LOG_TRACE, 3, "stss:%x count:%d", stss, stss->subs.GetCount()));
2956 if(!stss->animated)
2958 iSegment++;
2959 subIndex = 1;
2961 else
2963 int start, end;
2964 TranslateSegmentStartEnd(iSegment, m_fps, start, end);
2965 if(start+RTS_ANIMATE_SUBPIC_DUR*subIndex < end)
2966 subIndex++;
2967 else
2969 iSegment++;
2970 subIndex = 1;
2973 if(GetSegment(iSegment) != NULL)
2975 ASSERT(GetSegment(iSegment)->subs.GetCount()>0);
2976 return (POSITION)(subIndex | (iSegment<<RTS_POS_SEGMENT_INDEX_BITS));
2978 else
2979 return NULL;
2982 //@return: <0 if segment not found
2983 STDMETHODIMP_(REFERENCE_TIME) CRenderedTextSubtitle::GetStart(POSITION pos, double fps)
2985 //return(10000i64 * TranslateSegmentStart((int)pos-1, fps));
2986 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2987 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2988 int start = TranslateSegmentStart(iSegment, fps);
2989 const STSSegment *stss = GetSegment(iSegment);
2990 if(stss!=NULL)
2992 return (start + (subIndex-1)*RTS_ANIMATE_SUBPIC_DUR)*10000i64;
2994 else
2996 return -1;
3000 //@return: <0 if segment not found
3001 STDMETHODIMP_(REFERENCE_TIME) CRenderedTextSubtitle::GetStop(POSITION pos, double fps)
3003 // return(10000i64 * TranslateSegmentEnd((int)pos-1, fps));
3004 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3005 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
3006 int start, end, ret;
3007 TranslateSegmentStartEnd(iSegment, fps, start, end);
3008 const STSSegment *stss = GetSegment(iSegment);
3009 if(stss!=NULL)
3011 if(!stss->animated)
3012 ret = end;
3013 else
3015 ret = start+subIndex*RTS_ANIMATE_SUBPIC_DUR;
3016 if(ret > end)
3017 ret = end;
3019 return ret*10000i64;
3021 else
3022 return -1;
3025 //@start, @stop: -1 if segment not found; @stop may < @start if subIndex exceed uppper bound
3026 STDMETHODIMP_(VOID) CRenderedTextSubtitle::GetStartStop(POSITION pos, double fps, /*out*/REFERENCE_TIME &start, /*out*/REFERENCE_TIME &stop)
3028 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3029 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
3030 int tempStart, tempEnd;
3031 TranslateSegmentStartEnd(iSegment, fps, tempStart, tempEnd);
3032 start = tempStart;
3033 stop = tempEnd;
3034 const STSSegment *stss = GetSegment(iSegment);
3035 if(stss!=NULL)
3037 if(stss->animated)
3039 start += (subIndex-1)*RTS_ANIMATE_SUBPIC_DUR;
3040 if(start+RTS_ANIMATE_SUBPIC_DUR < stop)
3041 stop = start+RTS_ANIMATE_SUBPIC_DUR;
3043 //DbgLog((LOG_TRACE, 3, "animated:%d seg:%d idx:%d start:%d stop:%lu", stss->animated, iSegment, subIndex, (ULONG)start, (ULONG)stop));
3044 start *= 10000i64;
3045 stop *= 10000i64;
3047 else
3049 start = -1;
3050 stop = -1;
3054 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsAnimated(POSITION pos)
3056 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3057 if(iSegment>=0 && iSegment<m_segments.GetCount())
3058 return m_segments[iSegment].animated;
3059 else
3060 return false;
3061 //return(true);
3064 struct LSub {int idx, layer, readorder;};
3066 static int lscomp(const void* ls1, const void* ls2)
3068 int ret = ((LSub*)ls1)->layer - ((LSub*)ls2)->layer;
3069 if(!ret) ret = ((LSub*)ls1)->readorder - ((LSub*)ls2)->readorder;
3070 return(ret);
3073 STDMETHODIMP CRenderedTextSubtitle::RenderEx(SubPicDesc& spd, REFERENCE_TIME rt, double fps, CAtlList<CRect>& rectList)
3075 CRect bbox2(0,0,0,0);
3076 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))
3077 Init(CSize(spd.w, spd.h), spd.vidrect);
3078 int t = (int)(rt / 10000);
3079 int segment;
3080 //const
3081 STSSegment* stss = SearchSubs2(t, fps, &segment);
3082 if(!stss) return S_FALSE;
3083 // clear any cached subs not in the range of +/-30secs measured from the segment's bounds
3085 POSITION pos = m_subtitleCache.GetStartPosition();
3086 while(pos)
3088 int key;
3089 CSubtitle* value;
3090 m_subtitleCache.GetNextAssoc(pos, key, value);
3091 STSEntry& stse = m_entries.GetAt(key);
3092 if(stse.end <= (t-30000) || stse.start > (t+30000))
3094 delete value;
3095 m_subtitleCache.RemoveKey(key);
3096 pos = m_subtitleCache.GetStartPosition();
3100 m_sla.AdvanceToSegment(segment, stss->subs);
3101 CAtlArray<LSub> subs;
3102 for(int i = 0, j = stss->subs.GetCount(); i < j; i++)
3104 LSub ls;
3105 ls.idx = stss->subs[i];
3106 ls.layer = m_entries.GetAt(stss->subs[i]).layer;
3107 ls.readorder = m_entries.GetAt(stss->subs[i]).readorder;
3108 subs.Add(ls);
3110 qsort(subs.GetData(), subs.GetCount(), sizeof(LSub), lscomp);
3112 CompositeDrawItemListList drawItemListList;
3113 for(int i = 0, j = subs.GetCount(); i < j; i++)
3115 int entry = subs[i].idx;
3116 STSEntry stse = m_entries.GetAt(entry);
3118 int start = TranslateStart(entry, fps);
3119 m_time = t - start;
3120 m_delay = TranslateEnd(entry, fps) - start;
3122 CSubtitle* s = GetSubtitle(entry);
3123 if(!s) continue;
3124 stss->animated |= s->m_fAnimated2;
3125 CRect clipRect = s->m_clip;
3126 CRect r = s->m_rect;
3127 CSize spaceNeeded = r.Size();
3128 // apply the effects
3129 bool fPosOverride = false, fOrgOverride = false;
3130 int alpha = 0x00;
3131 CPoint org2;
3132 for(int k = 0; k < EF_NUMBEROFEFFECTS; k++)
3134 if(!s->m_effects[k]) continue;
3135 switch(k)
3137 case EF_MOVE: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3], t1=t[0], t2=t[1])}
3139 CPoint p;
3140 CPoint p1(s->m_effects[k]->param[0], s->m_effects[k]->param[1]);
3141 CPoint p2(s->m_effects[k]->param[2], s->m_effects[k]->param[3]);
3142 int t1 = s->m_effects[k]->t[0];
3143 int t2 = s->m_effects[k]->t[1];
3144 if(t2 < t1) {int t = t1; t1 = t2; t2 = t;}
3145 if(t1 <= 0 && t2 <= 0) {t1 = 0; t2 = m_delay;}
3146 if(m_time <= t1) p = p1;
3147 else if (p1 == p2) p = p1;
3148 else if(t1 < m_time && m_time < t2)
3150 double t = 1.0*(m_time-t1)/(t2-t1);
3151 p.x = (int)((1-t)*p1.x + t*p2.x);
3152 p.y = (int)((1-t)*p1.y + t*p2.y);
3154 else p = p2;
3155 r = CRect(
3156 CPoint((s->m_scrAlignment%3) == 1 ? p.x : (s->m_scrAlignment%3) == 0 ? p.x - spaceNeeded.cx : p.x - (spaceNeeded.cx+1)/2,
3157 s->m_scrAlignment <= 3 ? p.y - spaceNeeded.cy : s->m_scrAlignment <= 6 ? p.y - (spaceNeeded.cy+1)/2 : p.y),
3158 spaceNeeded);
3159 if(s->m_relativeTo == 1)
3160 r.OffsetRect(m_vidrect.TopLeft());
3161 fPosOverride = true;
3163 break;
3164 case EF_ORG: // {\org(x=param[0], y=param[1])}
3166 org2 = CPoint(s->m_effects[k]->param[0], s->m_effects[k]->param[1]);
3167 fOrgOverride = true;
3169 break;
3170 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])
3172 int t1 = s->m_effects[k]->t[0];
3173 int t2 = s->m_effects[k]->t[1];
3174 int t3 = s->m_effects[k]->t[2];
3175 int t4 = s->m_effects[k]->t[3];
3176 if(t1 == -1 && t4 == -1) {t1 = 0; t3 = m_delay-t3; t4 = m_delay;}
3177 if(m_time < t1) alpha = s->m_effects[k]->param[0];
3178 else if(m_time >= t1 && m_time < t2)
3180 double t = 1.0 * (m_time - t1) / (t2 - t1);
3181 alpha = (int)(s->m_effects[k]->param[0]*(1-t) + s->m_effects[k]->param[1]*t);
3183 else if(m_time >= t2 && m_time < t3) alpha = s->m_effects[k]->param[1];
3184 else if(m_time >= t3 && m_time < t4)
3186 double t = 1.0 * (m_time - t3) / (t4 - t3);
3187 alpha = (int)(s->m_effects[k]->param[1]*(1-t) + s->m_effects[k]->param[2]*t);
3189 else if(m_time >= t4) alpha = s->m_effects[k]->param[2];
3191 break;
3192 case EF_BANNER: // Banner;delay=param[0][;leftoright=param[1];fadeawaywidth=param[2]]
3194 int left = s->m_relativeTo == 1 ? m_vidrect.left : 0,
3195 right = s->m_relativeTo == 1 ? m_vidrect.right : m_size.cx;
3196 r.left = !!s->m_effects[k]->param[1]
3197 ? (left/*marginRect.left*/ - spaceNeeded.cx) + (int)(m_time*8.0/s->m_effects[k]->param[0])
3198 : (right /*- marginRect.right*/) - (int)(m_time*8.0/s->m_effects[k]->param[0]);
3199 r.right = r.left + spaceNeeded.cx;
3200 clipRect &= CRect(left>>3, clipRect.top, right>>3, clipRect.bottom);
3201 fPosOverride = true;
3203 break;
3204 case EF_SCROLL: // Scroll up/down(toptobottom=param[3]);top=param[0];bottom=param[1];delay=param[2][;fadeawayheight=param[4]]
3206 r.top = !!s->m_effects[k]->param[3]
3207 ? s->m_effects[k]->param[0] + (int)(m_time*8.0/s->m_effects[k]->param[2]) - spaceNeeded.cy
3208 : s->m_effects[k]->param[1] - (int)(m_time*8.0/s->m_effects[k]->param[2]);
3209 r.bottom = r.top + spaceNeeded.cy;
3210 CRect cr(0, (s->m_effects[k]->param[0] + 4) >> 3, spd.w, (s->m_effects[k]->param[1] + 4) >> 3);
3211 if(s->m_relativeTo == 1)
3212 r.top += m_vidrect.top,
3213 r.bottom += m_vidrect.top,
3214 cr.top += m_vidrect.top>>3,
3215 cr.bottom += m_vidrect.top>>3;
3216 clipRect &= cr;
3217 fPosOverride = true;
3219 break;
3220 default:
3221 break;
3224 if(!fPosOverride && !fOrgOverride && !s->m_fAnimated)
3225 r = m_sla.AllocRect(s, segment, entry, stse.layer, m_collisions);
3226 CPoint org;
3227 org.x = (s->m_scrAlignment%3) == 1 ? r.left : (s->m_scrAlignment%3) == 2 ? r.CenterPoint().x : r.right;
3228 org.y = s->m_scrAlignment <= 3 ? r.bottom : s->m_scrAlignment <= 6 ? r.CenterPoint().y : r.top;
3229 if(!fOrgOverride) org2 = org;
3230 SharedArrayByte pAlphaMask;
3231 if( s->m_pClipper )
3232 pAlphaMask = s->m_pClipper->m_pAlphaMask;
3233 CPoint p, p2(0, r.top);
3234 POSITION pos;
3235 p = p2;
3236 // Rectangles for inverse clip
3237 CRect iclipRect[4];
3238 iclipRect[0] = CRect(0, 0, spd.w, clipRect.top);
3239 iclipRect[1] = CRect(0, clipRect.top, clipRect.left, clipRect.bottom);
3240 iclipRect[2] = CRect(clipRect.right, clipRect.top, spd.w, clipRect.bottom);
3241 iclipRect[3] = CRect(0, clipRect.bottom, spd.w, spd.h);
3242 int dbgTest = 0;
3243 bbox2 = CRect(0,0,0,0);
3244 pos = s->GetHeadLinePosition();
3245 CompositeDrawItemList& drawItemList = drawItemListList.GetAt(drawItemListList.AddTail());
3246 while(pos)
3248 CLine* l = s->GetNextLine(pos);
3249 p.x = (s->m_scrAlignment%3) == 1 ? org.x
3250 : (s->m_scrAlignment%3) == 0 ? org.x - l->m_width
3251 : org.x - (l->m_width/2);
3253 CompositeDrawItemList tmpDrawItemList;
3254 if (s->m_clipInverse)
3256 for (int i=0;i<l->GetWordCount();i++)
3258 tmpDrawItemList.AddTail();
3259 tmpDrawItemList.AddTail();
3260 tmpDrawItemList.AddTail();
3261 tmpDrawItemList.AddTail();
3263 bbox2 |= l->PaintAll(&tmpDrawItemList, spd, iclipRect[0], pAlphaMask, p, org2, m_time, alpha);
3264 bbox2 |= l->PaintAll(&tmpDrawItemList, spd, iclipRect[1], pAlphaMask, p, org2, m_time, alpha);
3265 bbox2 |= l->PaintAll(&tmpDrawItemList, spd, iclipRect[2], pAlphaMask, p, org2, m_time, alpha);
3266 bbox2 |= l->PaintAll(&tmpDrawItemList, spd, iclipRect[3], pAlphaMask, p, org2, m_time, alpha);
3268 else
3270 for (int i=0;i<l->GetWordCount();i++)
3272 tmpDrawItemList.AddTail();
3274 bbox2 |= l->PaintAll(&tmpDrawItemList, spd, clipRect, pAlphaMask, p, org2, m_time, alpha);
3276 drawItemList.AddTailList(&tmpDrawItemList);
3277 p.y += l->m_ascent + l->m_descent;
3279 rectList.AddTail(bbox2);
3282 Draw(spd, drawItemListList);
3283 return (subs.GetCount() && !rectList.IsEmpty()) ? S_OK : S_FALSE;
3287 STDMETHODIMP CRenderedTextSubtitle::Render(SubPicDesc& spd, REFERENCE_TIME rt, double fps, RECT& bbox)
3289 CAtlList<CRect> rectList;
3290 HRESULT result = RenderEx(spd, rt, fps, rectList);
3291 POSITION pos = rectList.GetHeadPosition();
3292 CRect bbox2(0,0,0,0);
3293 while(pos!=NULL)
3295 bbox2 |= rectList.GetNext(pos);
3297 bbox = bbox2;
3298 return result;
3301 // IPersist
3303 STDMETHODIMP CRenderedTextSubtitle::GetClassID(CLSID* pClassID)
3305 return pClassID ? *pClassID = __uuidof(this), S_OK : E_POINTER;
3308 // ISubStream
3310 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStreamCount()
3312 return(1);
3315 STDMETHODIMP CRenderedTextSubtitle::GetStreamInfo(int iStream, WCHAR** ppName, LCID* pLCID)
3317 if(iStream != 0) return E_INVALIDARG;
3318 if(ppName)
3320 if(!(*ppName = (WCHAR*)CoTaskMemAlloc((m_name.GetLength()+1)*sizeof(WCHAR))))
3321 return E_OUTOFMEMORY;
3322 wcscpy(*ppName, CStringW(m_name));
3324 if(pLCID)
3326 *pLCID = 0; // TODO
3328 return S_OK;
3331 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStream()
3333 return(0);
3336 STDMETHODIMP CRenderedTextSubtitle::SetStream(int iStream)
3338 return iStream == 0 ? S_OK : E_FAIL;
3341 STDMETHODIMP CRenderedTextSubtitle::Reload()
3343 CFileStatus s;
3344 if(!CFile::GetStatus(m_path, s)) return E_FAIL;
3345 return !m_path.IsEmpty() && Open(m_path, DEFAULT_CHARSET) ? S_OK : E_FAIL;
3348 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsColorTypeSupported( int type )
3350 return type==MSP_AY11 ||
3351 type==MSP_AYUV ||
3352 type==MSP_AUYV ||
3353 type==MSP_RGBA;
3356 void CRenderedTextSubtitle::Draw( SubPicDesc& spd, CompositeDrawItemListList& drawItemListList )
3358 POSITION list_pos = drawItemListList.GetHeadPosition();
3359 while(list_pos)
3361 CompositeDrawItemList& drawItemList = drawItemListList.GetNext(list_pos);
3362 POSITION item_pos = drawItemList.GetHeadPosition();
3363 while(item_pos)
3365 CompositeDrawItem& draw_item = drawItemList.GetNext(item_pos);
3366 if(draw_item.shadow)
3367 Rasterizer::Draw( spd, *draw_item.shadow );
3369 item_pos = drawItemList.GetHeadPosition();
3370 while(item_pos)
3372 CompositeDrawItem& draw_item = drawItemList.GetNext(item_pos);
3373 if(draw_item.outline)
3374 Rasterizer::Draw( spd, *draw_item.outline );
3376 item_pos = drawItemList.GetHeadPosition();
3377 while(item_pos)
3379 CompositeDrawItem& draw_item = drawItemList.GetNext(item_pos);
3380 if(draw_item.body)
3381 Rasterizer::Draw( spd, *draw_item.body );