Major refactor on the rendering pipe-line, though it should not affect anything yet.
[xy_vsfilter.git] / src / subtitles / RTS.cpp
blob62fc3ce9f09535a47d79f2d7eba24e58a8a0d80f
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& org, OverlayList* overlay_list )
194 if(!word->m_str || overlay_list==NULL) return;
195 bool error = false;
198 CPoint trans_org = org - p;
199 bool need_transform = word->NeedTransform();
200 if(!need_transform)
202 trans_org.x=0;
203 trans_org.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_org);
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_org);
224 OverlayMruCache* overlay_cache = CacheManager::GetOverlayMruCache();
225 POSITION pos = overlay_cache->Lookup(overlay_key);
226 if(pos==NULL)
228 if( !word->DoPaint(psub, trans_org, &(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_org);
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, 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 //shadow
1218 if(w->m_style.get().shadowDepthX != 0 || w->m_style.get().shadowDepthY != 0)
1220 int x = p.x + (int)(w->m_style.get().shadowDepthX+0.5);
1221 int y = p.y + m_ascent - w->m_ascent + (int)(w->m_style.get().shadowDepthY+0.5);
1222 DWORD a = 0xff - w->m_style.get().alpha[3];
1223 if(alpha > 0) a = MulDiv(a, 0xff - alpha, 0xff);
1224 COLORREF shadow = revcolor(w->m_style.get().colors[3]) | (a<<24);
1225 DWORD sw[6] = {shadow, -1};
1226 //xy
1227 if(spd.type == MSP_AUYV)
1229 sw[0] =rgb2yuv(sw[0], XY_AUYV);
1231 else if(spd.type == MSP_AYUV || spd.type == MSP_AY11)
1233 sw[0] =rgb2yuv(sw[0], XY_AYUV);
1235 OverlayList overlay_list;
1236 CWord::Paint(w, CPoint(x, y), org, &overlay_list);
1237 if(w->m_style.get().borderStyle == 0)
1239 outputItem.shadow.reset(
1240 Rasterizer::CreateDrawItem(spd, overlay_list.overlay, clipRect, pAlphaMask, x, y, sw,
1241 w->m_ktype > 0 || w->m_style.get().alpha[0] < 0xff,
1242 (w->m_style.get().outlineWidthX+w->m_style.get().outlineWidthY > 0) && !(w->m_ktype == 2 && time < w->m_kstart))
1244 bbox |= Rasterizer::DryDraw(spd, *outputItem.shadow);
1246 else if(w->m_style.get().borderStyle == 1 && w->m_pOpaqueBox)
1248 outputItem.shadow.reset(
1249 Rasterizer::CreateDrawItem(spd, overlay_list.next->overlay, clipRect, pAlphaMask, x, y, sw, true, false)
1251 bbox |= Rasterizer::DryDraw(spd, *outputItem.shadow);
1255 //outline
1257 if(w->m_style.get().outlineWidthX+w->m_style.get().outlineWidthY > 0 && !(w->m_ktype == 2 && time < w->m_kstart))
1259 int x = p.x;
1260 int y = p.y + m_ascent - w->m_ascent;
1261 DWORD aoutline = w->m_style.get().alpha[2];
1262 if(alpha > 0) aoutline += MulDiv(alpha, 0xff - w->m_style.get().alpha[2], 0xff);
1263 COLORREF outline = revcolor(w->m_style.get().colors[2]) | ((0xff-aoutline)<<24);
1264 DWORD sw[6] = {outline, -1};
1265 //xy
1266 if(spd.type == MSP_AUYV)
1268 sw[0] =rgb2yuv(sw[0], XY_AUYV);
1270 else if(spd.type == MSP_AYUV || spd.type == MSP_AY11)
1272 sw[0] =rgb2yuv(sw[0], XY_AYUV);
1274 OverlayList overlay_list;
1275 CWord::Paint(w, CPoint(x, y), org, &overlay_list);
1276 if(w->m_style.get().borderStyle == 0)
1278 outputItem.outline.reset(
1279 Rasterizer::CreateDrawItem(spd, overlay_list.overlay, clipRect, pAlphaMask, x, y, sw, !w->m_style.get().alpha[0] && !w->m_style.get().alpha[1] && !alpha, true)
1281 bbox |= Rasterizer::DryDraw(spd, *outputItem.outline);
1283 else if(w->m_style.get().borderStyle == 1 && w->m_pOpaqueBox)
1285 outputItem.outline.reset(
1286 Rasterizer::CreateDrawItem(spd, overlay_list.next->overlay, clipRect, pAlphaMask, x, y, sw, true, false)
1288 bbox |= Rasterizer::DryDraw(spd, *outputItem.outline);
1292 //body
1294 int x = p.x;
1295 int y = p.y + m_ascent - w->m_ascent;
1296 // colors
1297 DWORD aprimary = w->m_style.get().alpha[0];
1298 if(alpha > 0) aprimary += MulDiv(alpha, 0xff - w->m_style.get().alpha[0], 0xff);
1299 COLORREF primary = revcolor(w->m_style.get().colors[0]) | ((0xff-aprimary)<<24);
1300 DWORD asecondary = w->m_style.get().alpha[1];
1301 if(alpha > 0) asecondary += MulDiv(alpha, 0xff - w->m_style.get().alpha[1], 0xff);
1302 COLORREF secondary = revcolor(w->m_style.get().colors[1]) | ((0xff-asecondary)<<24);
1303 DWORD sw[6] = {primary, 0, secondary};
1304 // karaoke
1305 double t;
1306 if(w->m_ktype == 0 || w->m_ktype == 2)
1308 t = time < w->m_kstart ? 0 : 1;
1310 else if(w->m_ktype == 1)
1312 if(time < w->m_kstart) t = 0;
1313 else if(time < w->m_kend)
1315 t = 1.0 * (time - w->m_kstart) / (w->m_kend - w->m_kstart);
1316 double angle = fmod(w->m_style.get().fontAngleZ, 360.0);
1317 if(angle > 90 && angle < 270)
1319 t = 1-t;
1320 COLORREF tmp = sw[0];
1321 sw[0] = sw[2];
1322 sw[2] = tmp;
1325 else t = 1.0;
1327 if(t >= 1)
1329 sw[1] = 0xffffffff;
1331 sw[3] = (int)(w->m_style.get().outlineWidthX + t*w->m_width) >> 3;
1332 sw[4] = sw[2];
1333 sw[5] = 0x00ffffff;
1334 //xy
1335 if(spd.type == MSP_AUYV)
1337 sw[0] =rgb2yuv(sw[0], XY_AUYV);
1338 sw[2] =rgb2yuv(sw[2], XY_AUYV);
1339 sw[4] =rgb2yuv(sw[4], XY_AUYV);
1341 else if(spd.type == MSP_AYUV || spd.type == MSP_AY11)
1343 sw[0] =rgb2yuv(sw[0], XY_AYUV);
1344 sw[2] =rgb2yuv(sw[2], XY_AYUV);
1345 sw[4] =rgb2yuv(sw[4], XY_AYUV);
1347 OverlayList overlay_list;
1348 CWord::Paint(w, CPoint(x, y), org, &overlay_list);
1349 outputItem.body.reset(
1350 Rasterizer::CreateDrawItem(spd, overlay_list.overlay, clipRect, pAlphaMask, x, y, sw, true, false)
1352 bbox |= Rasterizer::DryDraw(spd, *outputItem.body);
1354 p.x += w->m_width;
1356 return(bbox);
1359 void CLine::AddWord2Tail( SharedPtrCWord words )
1361 __super::AddTail(words);
1364 bool CLine::IsEmpty()
1366 return __super::IsEmpty();
1369 int CLine::GetWordCount()
1371 return GetCount();
1374 // CSubtitle
1376 CSubtitle::CSubtitle()
1378 memset(m_effects, 0, sizeof(Effect*)*EF_NUMBEROFEFFECTS);
1379 m_pClipper = NULL;
1380 m_clipInverse = false;
1381 m_scalex = m_scaley = 1;
1382 m_fAnimated2 = false;
1385 CSubtitle::~CSubtitle()
1387 Empty();
1390 void CSubtitle::Empty()
1392 POSITION pos = GetHeadPosition();
1393 while(pos) delete GetNext(pos);
1394 // pos = m_words.GetHeadPosition();
1395 // while(pos) delete m_words.GetNext(pos);
1396 for(int i = 0; i < EF_NUMBEROFEFFECTS; i++) {if(m_effects[i]) delete m_effects[i];}
1397 memset(m_effects, 0, sizeof(Effect*)*EF_NUMBEROFEFFECTS);
1398 if(m_pClipper) delete m_pClipper;
1399 m_pClipper = NULL;
1402 int CSubtitle::GetFullWidth()
1404 int width = 0;
1405 POSITION pos = m_words.GetHeadPosition();
1406 while(pos) width += m_words.GetNext(pos)->m_width;
1407 return(width);
1410 int CSubtitle::GetFullLineWidth(POSITION pos)
1412 int width = 0;
1413 while(pos)
1415 SharedPtrCWord w = m_words.GetNext(pos);
1416 if(w->m_fLineBreak) break;
1417 width += w->m_width;
1419 return(width);
1422 int CSubtitle::GetWrapWidth(POSITION pos, int maxwidth)
1424 if(m_wrapStyle == 0 || m_wrapStyle == 3)
1426 if(maxwidth > 0)
1428 // int fullwidth = GetFullWidth();
1429 int fullwidth = GetFullLineWidth(pos);
1430 int minwidth = fullwidth / ((abs(fullwidth) / maxwidth) + 1);
1431 int width = 0, wordwidth = 0;
1432 while(pos && width < minwidth)
1434 SharedPtrCWord w = m_words.GetNext(pos);
1435 wordwidth = w->m_width;
1436 if(abs(width + wordwidth) < abs(maxwidth)) width += wordwidth;
1438 maxwidth = width;
1439 if(m_wrapStyle == 3 && pos) maxwidth -= wordwidth;
1442 else if(m_wrapStyle == 1)
1444 // maxwidth = maxwidth;
1446 else if(m_wrapStyle == 2)
1448 maxwidth = INT_MAX;
1450 return(maxwidth);
1453 CLine* CSubtitle::GetNextLine(POSITION& pos, int maxwidth)
1455 if(pos == NULL) return(NULL);
1456 CLine* ret = new CLine();
1457 if(!ret) return(NULL);
1458 ret->m_width = ret->m_ascent = ret->m_descent = ret->m_borderX = ret->m_borderY = 0;
1459 maxwidth = GetWrapWidth(pos, maxwidth);
1460 bool fEmptyLine = true;
1461 while(pos)
1463 SharedPtrCWord w = m_words.GetNext(pos);
1464 if(ret->m_ascent < w->m_ascent) ret->m_ascent = w->m_ascent;
1465 if(ret->m_descent < w->m_descent) ret->m_descent = w->m_descent;
1466 if(ret->m_borderX < w->m_style.get().outlineWidthX) ret->m_borderX = (int)(w->m_style.get().outlineWidthX+0.5);
1467 if(ret->m_borderY < w->m_style.get().outlineWidthY) ret->m_borderY = (int)(w->m_style.get().outlineWidthY+0.5);
1468 if(w->m_fLineBreak)
1470 if(fEmptyLine) {ret->m_ascent /= 2; ret->m_descent /= 2; ret->m_borderX = ret->m_borderY = 0;}
1471 ret->Compact();
1472 return(ret);
1474 fEmptyLine = false;
1475 bool fWSC = w->m_fWhiteSpaceChar;
1476 int width = w->m_width;
1477 POSITION pos2 = pos;
1478 while(pos2)
1480 if(m_words.GetAt(pos2)->m_fWhiteSpaceChar != fWSC
1481 || m_words.GetAt(pos2)->m_fLineBreak) break;
1482 SharedPtrCWord w2 = m_words.GetNext(pos2);
1483 width += w2->m_width;
1485 if((ret->m_width += width) <= maxwidth || ret->IsEmpty())
1487 ret->AddWord2Tail(w);
1488 while(pos != pos2)
1490 ret->AddWord2Tail(m_words.GetNext(pos));
1492 pos = pos2;
1494 else
1496 if(pos) m_words.GetPrev(pos);
1497 else pos = m_words.GetTailPosition();
1498 ret->m_width -= width;
1499 break;
1502 ret->Compact();
1503 return(ret);
1506 void CSubtitle::CreateClippers(CSize size)
1508 size.cx >>= 3;
1509 size.cy >>= 3;
1510 if(m_effects[EF_BANNER] && m_effects[EF_BANNER]->param[2])
1512 int width = m_effects[EF_BANNER]->param[2];
1513 int w = size.cx, h = size.cy;
1514 if(!m_pClipper)
1516 CStringW str;
1517 str.Format(L"m %d %d l %d %d %d %d %d %d", 0, 0, w, 0, w, h, 0, h);
1518 m_pClipper = new CClipper(str, size, 1, 1, false);
1519 if(!m_pClipper) return;
1521 int da = (64<<8)/width;
1522 BYTE* am = m_pClipper->m_pAlphaMask.get();
1523 for(int j = 0; j < h; j++, am += w)
1525 int a = 0;
1526 int k = min(width, w);
1527 for(int i = 0; i < k; i++, a += da)
1528 am[i] = (am[i]*a)>>14;
1529 a = 0x40<<8;
1530 k = w-width;
1531 if(k < 0) {a -= -k*da; k = 0;}
1532 for(int i = k; i < w; i++, a -= da)
1533 am[i] = (am[i]*a)>>14;
1536 else if(m_effects[EF_SCROLL] && m_effects[EF_SCROLL]->param[4])
1538 int height = m_effects[EF_SCROLL]->param[4];
1539 int w = size.cx, h = size.cy;
1540 if(!m_pClipper)
1542 CStringW str;
1543 str.Format(L"m %d %d l %d %d %d %d %d %d", 0, 0, w, 0, w, h, 0, h);
1544 m_pClipper = new CClipper(str, size, 1, 1, false);
1545 if(!m_pClipper) return;
1547 int da = (64<<8)/height;
1548 int a = 0;
1549 int k = m_effects[EF_SCROLL]->param[0]>>3;
1550 int l = k+height;
1551 if(k < 0) {a += -k*da; k = 0;}
1552 if(l > h) {l = h;}
1553 if(k < h)
1555 BYTE* am = &m_pClipper->m_pAlphaMask[k*w];
1556 memset(m_pClipper->m_pAlphaMask.get(), 0, am - m_pClipper->m_pAlphaMask.get());
1557 for(int j = k; j < l; j++, a += da)
1559 for(int i = 0; i < w; i++, am++)
1560 *am = ((*am)*a)>>14;
1563 da = -(64<<8)/height;
1564 a = 0x40<<8;
1565 l = m_effects[EF_SCROLL]->param[1]>>3;
1566 k = l-height;
1567 if(k < 0) {a += -k*da; k = 0;}
1568 if(l > h) {l = h;}
1569 if(k < h)
1571 BYTE* am = &m_pClipper->m_pAlphaMask[k*w];
1572 int j = k;
1573 for(; j < l; j++, a += da)
1575 for(int i = 0; i < w; i++, am++)
1576 *am = ((*am)*a)>>14;
1578 memset(am, 0, (h-j)*w);
1583 void CSubtitle::MakeLines(CSize size, CRect marginRect)
1585 CSize spaceNeeded(0, 0);
1586 bool fFirstLine = true;
1587 m_topborder = m_bottomborder = 0;
1588 CLine* l = NULL;
1589 POSITION pos = m_words.GetHeadPosition();
1590 while(pos)
1592 l = GetNextLine(pos, size.cx - marginRect.left - marginRect.right);
1593 if(!l) break;
1594 if(fFirstLine) {m_topborder = l->m_borderY; fFirstLine = false;}
1595 spaceNeeded.cx = max(l->m_width+l->m_borderX, spaceNeeded.cx);
1596 spaceNeeded.cy += l->m_ascent + l->m_descent;
1597 AddTail(l);
1599 if(l) m_bottomborder = l->m_borderY;
1600 m_rect = CRect(
1601 CPoint((m_scrAlignment%3) == 1 ? marginRect.left
1602 : (m_scrAlignment%3) == 2 ? (marginRect.left + (size.cx - marginRect.right) - spaceNeeded.cx + 1) / 2
1603 : (size.cx - marginRect.right - spaceNeeded.cx),
1604 m_scrAlignment <= 3 ? (size.cy - marginRect.bottom - spaceNeeded.cy)
1605 : m_scrAlignment <= 6 ? (marginRect.top + (size.cy - marginRect.bottom) - spaceNeeded.cy + 1) / 2
1606 : marginRect.top),
1607 spaceNeeded);
1610 POSITION CSubtitle::GetHeadLinePosition()
1612 return __super::GetHeadPosition();
1615 CLine* CSubtitle::GetNextLine( POSITION& pos )
1617 return __super::GetNext(pos);
1620 // CScreenLayoutAllocator
1622 void CScreenLayoutAllocator::Empty()
1624 m_subrects.RemoveAll();
1627 void CScreenLayoutAllocator::AdvanceToSegment(int segment, const CAtlArray<int>& sa)
1629 POSITION pos = m_subrects.GetHeadPosition();
1630 while(pos)
1632 POSITION prev = pos;
1633 SubRect& sr = m_subrects.GetNext(pos);
1634 bool fFound = false;
1635 if(abs(sr.segment - segment) <= 1) // using abs() makes it possible to play the subs backwards, too :)
1637 for(size_t i = 0; i < sa.GetCount() && !fFound; i++)
1639 if(sa[i] == sr.entry)
1641 sr.segment = segment;
1642 fFound = true;
1646 if(!fFound) m_subrects.RemoveAt(prev);
1650 CRect CScreenLayoutAllocator::AllocRect(CSubtitle* s, int segment, int entry, int layer, int collisions)
1652 // TODO: handle collisions == 1 (reversed collisions)
1653 POSITION pos = m_subrects.GetHeadPosition();
1654 while(pos)
1656 SubRect& sr = m_subrects.GetNext(pos);
1657 if(sr.segment == segment && sr.entry == entry)
1659 return(sr.r + CRect(0, -s->m_topborder, 0, -s->m_bottomborder));
1662 CRect r = s->m_rect + CRect(0, s->m_topborder, 0, s->m_bottomborder);
1663 bool fSearchDown = s->m_scrAlignment > 3;
1664 bool fOK;
1667 fOK = true;
1668 pos = m_subrects.GetHeadPosition();
1669 while(pos)
1671 SubRect& sr = m_subrects.GetNext(pos);
1672 if(layer == sr.layer && !(r & sr.r).IsRectEmpty())
1674 if(fSearchDown)
1676 r.bottom = sr.r.bottom + r.Height();
1677 r.top = sr.r.bottom;
1679 else
1681 r.top = sr.r.top - r.Height();
1682 r.bottom = sr.r.top;
1684 fOK = false;
1688 while(!fOK);
1689 SubRect sr;
1690 sr.r = r;
1691 sr.segment = segment;
1692 sr.entry = entry;
1693 sr.layer = layer;
1694 m_subrects.AddTail(sr);
1695 return(sr.r + CRect(0, -s->m_topborder, 0, -s->m_bottomborder));
1698 // CRenderedTextSubtitle
1700 CAtlMap<CStringW, CRenderedTextSubtitle::AssCmdType, CStringElementTraits<CStringW>> CRenderedTextSubtitle::m_cmdMap;
1702 CRenderedTextSubtitle::CRenderedTextSubtitle(CCritSec* pLock)
1703 : CSubPicProviderImpl(pLock)
1705 if( m_cmdMap.IsEmpty() )
1707 InitCmdMap();
1709 m_size = CSize(0, 0);
1710 if(g_hDC_refcnt == 0)
1712 g_hDC = CreateCompatibleDC(NULL);
1713 SetBkMode(g_hDC, TRANSPARENT);
1714 SetTextColor(g_hDC, 0xffffff);
1715 SetMapMode(g_hDC, MM_TEXT);
1717 g_hDC_refcnt++;
1720 CRenderedTextSubtitle::~CRenderedTextSubtitle()
1722 Deinit();
1723 g_hDC_refcnt--;
1724 if(g_hDC_refcnt == 0) DeleteDC(g_hDC);
1727 void CRenderedTextSubtitle::InitCmdMap()
1729 if( m_cmdMap.IsEmpty() )
1731 m_cmdMap.SetAt(L"1c", CMD_1c);
1732 m_cmdMap.SetAt(L"2c", CMD_2c);
1733 m_cmdMap.SetAt(L"3c", CMD_3c);
1734 m_cmdMap.SetAt(L"4c", CMD_4c);
1735 m_cmdMap.SetAt(L"1a", CMD_1a);
1736 m_cmdMap.SetAt(L"2a", CMD_2a);
1737 m_cmdMap.SetAt(L"3a", CMD_3a);
1738 m_cmdMap.SetAt(L"4a", CMD_4a);
1739 m_cmdMap.SetAt(L"alpha", CMD_alpha);
1740 m_cmdMap.SetAt(L"an", CMD_an);
1741 m_cmdMap.SetAt(L"a", CMD_a);
1742 m_cmdMap.SetAt(L"blur", CMD_blur);
1743 m_cmdMap.SetAt(L"bord", CMD_bord);
1744 m_cmdMap.SetAt(L"be", CMD_be);
1745 m_cmdMap.SetAt(L"b", CMD_b);
1746 m_cmdMap.SetAt(L"clip", CMD_clip);
1747 m_cmdMap.SetAt(L"iclip", CMD_iclip);
1748 m_cmdMap.SetAt(L"c", CMD_c);
1749 m_cmdMap.SetAt(L"fade", CMD_fade);
1750 m_cmdMap.SetAt(L"fad", CMD_fad);
1751 m_cmdMap.SetAt(L"fax", CMD_fax);
1752 m_cmdMap.SetAt(L"fay", CMD_fay);
1753 m_cmdMap.SetAt(L"fe", CMD_fe);
1754 m_cmdMap.SetAt(L"fn", CMD_fn);
1755 m_cmdMap.SetAt(L"frx", CMD_frx);
1756 m_cmdMap.SetAt(L"fry", CMD_fry);
1757 m_cmdMap.SetAt(L"frz", CMD_frz);
1758 m_cmdMap.SetAt(L"fr", CMD_fr);
1759 m_cmdMap.SetAt(L"fscx", CMD_fscx);
1760 m_cmdMap.SetAt(L"fscy", CMD_fscy);
1761 m_cmdMap.SetAt(L"fsc", CMD_fsc);
1762 m_cmdMap.SetAt(L"fsp", CMD_fsp);
1763 m_cmdMap.SetAt(L"fs", CMD_fs);
1764 m_cmdMap.SetAt(L"i", CMD_i);
1765 m_cmdMap.SetAt(L"kt", CMD_kt);
1766 m_cmdMap.SetAt(L"kf", CMD_kf);
1767 m_cmdMap.SetAt(L"K", CMD_K);
1768 m_cmdMap.SetAt(L"ko", CMD_ko);
1769 m_cmdMap.SetAt(L"k", CMD_k);
1770 m_cmdMap.SetAt(L"move", CMD_move);
1771 m_cmdMap.SetAt(L"org", CMD_org);
1772 m_cmdMap.SetAt(L"pbo", CMD_pbo);
1773 m_cmdMap.SetAt(L"pos", CMD_pos);
1774 m_cmdMap.SetAt(L"p", CMD_p);
1775 m_cmdMap.SetAt(L"q", CMD_q);
1776 m_cmdMap.SetAt(L"r", CMD_r);
1777 m_cmdMap.SetAt(L"shad", CMD_shad);
1778 m_cmdMap.SetAt(L"s", CMD_s);
1779 m_cmdMap.SetAt(L"t", CMD_t);
1780 m_cmdMap.SetAt(L"u", CMD_u);
1781 m_cmdMap.SetAt(L"xbord", CMD_xbord);
1782 m_cmdMap.SetAt(L"xshad", CMD_xshad);
1783 m_cmdMap.SetAt(L"ybord", CMD_ybord);
1784 m_cmdMap.SetAt(L"yshad", CMD_yshad);
1788 void CRenderedTextSubtitle::Copy(CRenderedTextSubtitle& rts)
1790 __super::Copy(rts);
1791 m_size = rts.m_size;
1794 void CRenderedTextSubtitle::Copy(CSimpleTextSubtitle& sts)
1796 __super::Copy(sts);
1799 void CRenderedTextSubtitle::Empty()
1801 Deinit();
1802 __super::Empty();
1805 void CRenderedTextSubtitle::OnChanged()
1807 __super::OnChanged();
1808 POSITION pos = m_subtitleCache.GetStartPosition();
1809 while(pos)
1811 int i;
1812 CSubtitle* s;
1813 m_subtitleCache.GetNextAssoc(pos, i, s);
1814 delete s;
1816 m_subtitleCache.RemoveAll();
1817 m_sla.Empty();
1820 bool CRenderedTextSubtitle::Init(CSize size, CRect vidrect)
1822 Deinit();
1823 m_size = CSize(size.cx*8, size.cy*8);
1824 m_vidrect = CRect(vidrect.left*8, vidrect.top*8, vidrect.right*8, vidrect.bottom*8);
1825 m_sla.Empty();
1826 return(true);
1829 void CRenderedTextSubtitle::Deinit()
1831 POSITION pos = m_subtitleCache.GetStartPosition();
1832 while(pos)
1834 int i;
1835 CSubtitle* s;
1836 m_subtitleCache.GetNextAssoc(pos, i, s);
1837 delete s;
1839 m_subtitleCache.RemoveAll();
1840 m_sla.Empty();
1841 m_size = CSize(0, 0);
1842 m_vidrect.SetRectEmpty();
1844 CacheManager::GetCWordMruCache()->RemoveAll();
1845 CacheManager::GetPathDataMruCache()->RemoveAll();
1846 CacheManager::GetScanLineDataMruCache()->RemoveAll();
1847 CacheManager::GetOverlayNoBlurMruCache()->RemoveAll();
1848 CacheManager::GetOverlayMruCache()->RemoveAll();
1849 CacheManager::GetAssTagListMruCache()->RemoveAll();
1850 CacheManager::GetSubpixelVarianceCache()->RemoveAll();
1851 CacheManager::GetTextInfoCache()->RemoveAll();
1854 void CRenderedTextSubtitle::ParseEffect(CSubtitle* sub, const CStringW& str)
1856 CStringW::PCXSTR str_start = str.GetString();
1857 CStringW::PCXSTR str_end = str_start + str.GetLength();
1858 str_start = SkipWhiteSpaceLeft(str_start, str_end);
1860 if(!sub || *str_start==0)
1861 return;
1863 str_end = FastSkipWhiteSpaceRight(str_start, str_end);
1865 const WCHAR* s = FindChar(str_start, str_end, L';');
1866 if(*s==L';') {
1867 s++;
1870 const CStringW effect(str_start, s-str_start);
1871 if(!effect.CompareNoCase( L"Banner;" ) )
1873 int delay, lefttoright = 0, fadeawaywidth = 0;
1874 if(swscanf(s, L"%d;%d;%d", &delay, &lefttoright, &fadeawaywidth) < 1) return;
1875 Effect* e = new Effect;
1876 if(!e) return;
1877 sub->m_effects[e->type = EF_BANNER] = e;
1878 e->param[0] = (int)(max(1.0*delay/sub->m_scalex, 1));
1879 e->param[1] = lefttoright;
1880 e->param[2] = (int)(sub->m_scalex*fadeawaywidth);
1881 sub->m_wrapStyle = 2;
1883 else if(!effect.CompareNoCase(L"Scroll up;") || !effect.CompareNoCase(L"Scroll down;"))
1885 int top, bottom, delay, fadeawayheight = 0;
1886 if(swscanf(s, L"%d;%d;%d;%d", &top, &bottom, &delay, &fadeawayheight) < 3) return;
1887 if(top > bottom) {int tmp = top; top = bottom; bottom = tmp;}
1888 Effect* e = new Effect;
1889 if(!e) return;
1890 sub->m_effects[e->type = EF_SCROLL] = e;
1891 e->param[0] = (int)(sub->m_scaley*top*8);
1892 e->param[1] = (int)(sub->m_scaley*bottom*8);
1893 e->param[2] = (int)(max(1.0*delay/sub->m_scaley, 1));
1894 e->param[3] = (effect.GetLength() == 12);
1895 e->param[4] = (int)(sub->m_scaley*fadeawayheight);
1899 void CRenderedTextSubtitle::ParseString(CSubtitle* sub, CStringW str, const FwSTSStyle& style)
1901 if(!sub) return;
1902 str.Replace(L"\\N", L"\n");
1903 str.Replace(L"\\n", (sub->m_wrapStyle < 2 || sub->m_wrapStyle == 3) ? L" " : L"\n");
1904 str.Replace(L"\\h", L"\x00A0");
1905 for(int ite = 0, j = 0, len = str.GetLength(); j <= len; j++)
1907 WCHAR c = str[j];
1908 if(c != L'\n' && c != L' ' && c != L'\x00A0' && c != 0)
1909 continue;
1910 if(ite < j)
1912 if(PCWord tmp_ptr = new CText(style, str.Mid(ite, j-ite), m_ktype, m_kstart, m_kend))
1914 SharedPtrCWord w(tmp_ptr);
1915 sub->m_words.AddTail(w);
1917 else
1919 ///TODO: overflow handling
1921 m_kstart = m_kend;
1923 if(c == L'\n')
1925 if(PCWord tmp_ptr = new CText(style, CStringW(), m_ktype, m_kstart, m_kend))
1927 SharedPtrCWord w(tmp_ptr);
1928 sub->m_words.AddTail(w);
1930 else
1932 ///TODO: overflow handling
1934 m_kstart = m_kend;
1936 else if(c == L' ' || c == L'\x00A0')
1938 if(PCWord tmp_ptr = new CText(style, CStringW(c), m_ktype, m_kstart, m_kend))
1940 SharedPtrCWord w(tmp_ptr);
1941 sub->m_words.AddTail(w);
1943 else
1945 ///TODO: overflow handling
1947 m_kstart = m_kend;
1949 ite = j+1;
1951 return;
1954 void CRenderedTextSubtitle::ParsePolygon(CSubtitle* sub, const CStringW& str, const FwSTSStyle& style)
1956 if(!sub || !str.GetLength() || !m_nPolygon) return;
1958 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))
1960 SharedPtrCWord w(tmp_ptr);
1961 ///Todo: fix me
1962 //if( PCWord w_cache = m_wordCache.lookup(*w) )
1964 // sub->m_words.AddTail(w_cache);
1965 // delete w;
1967 //else
1969 sub->m_words.AddTail(w);
1971 m_kstart = m_kend;
1975 bool CRenderedTextSubtitle::ParseSSATag( AssTagList *assTags, const CStringW& str )
1977 if(!assTags) return(false);
1978 int nTags = 0, nUnrecognizedTags = 0;
1979 for(int i = 0, j; (j = str.Find(L'\\', i)) >= 0; i = j)
1981 POSITION pos = assTags->AddTail();
1982 AssTag& assTag = assTags->GetAt(pos);
1983 assTag.cmdType = CMD_COUNT;
1985 j++;
1986 CStringW::PCXSTR str_start = str.GetString() + j;
1987 CStringW::PCXSTR pc = str_start;
1988 while( iswspace(*pc) )
1990 pc++;
1992 j += pc-str_start;
1993 str_start = pc;
1994 while( *pc && *pc != L'(' && *pc != L'\\' )
1996 pc++;
1998 j += pc-str_start;
1999 if( pc-str_start>0 )
2001 while( iswspace(*--pc) );
2002 pc++;
2005 const CStringW cmd(str_start, pc-str_start);
2006 if(cmd.IsEmpty()) continue;
2008 CAtlArray<CStringW>& params = assTag.strParams;
2009 if(str[j] == L'(')
2011 j++;
2012 CStringW::PCXSTR str_start = str.GetString() + j;
2013 CStringW::PCXSTR pc = str_start;
2014 while( iswspace(*pc) )
2016 pc++;
2018 j += pc-str_start;
2019 str_start = pc;
2020 while( *pc && *pc != L')' )
2022 pc++;
2024 j += pc-str_start;
2025 if( pc-str_start>0 )
2027 while( iswspace(*--pc) );
2028 pc++;
2031 CStringW::PCXSTR param_start = str_start;
2032 CStringW::PCXSTR param_end = pc;
2033 while( param_start<param_end )
2035 param_start = SkipWhiteSpaceLeft(param_start, param_end);
2037 CStringW::PCXSTR newstart = FindChar(param_start, param_end, L',');
2038 CStringW::PCXSTR newend = FindChar(param_start, param_end, L'\\');
2039 if(newstart > param_start && newstart < newend)
2041 newstart = FastSkipWhiteSpaceRight(param_start, newstart);
2042 CStringW s(param_start, newstart - param_start);
2044 if(!s.IsEmpty()) params.Add(s);
2045 param_start = newstart + 1;
2047 else if(param_start<param_end)
2049 CStringW s(param_start, param_end - param_start);
2051 params.Add(s);
2052 param_start = param_end;
2057 AssCmdType cmd_type = CMD_COUNT;
2058 int cmd_length = min(MAX_CMD_LENGTH, cmd.GetLength());
2059 for( ;cmd_length>=MIN_CMD_LENGTH;cmd_length-- )
2061 if( m_cmdMap.Lookup(cmd.Left(cmd_length), cmd_type) )
2062 break;
2064 if(cmd_length<MIN_CMD_LENGTH)
2065 cmd_type = CMD_COUNT;
2066 switch( cmd_type )
2068 case CMD_fax:
2069 case CMD_fay:
2070 case CMD_fe:
2071 case CMD_fn:
2072 case CMD_frx:
2073 case CMD_fry:
2074 case CMD_frz:
2075 case CMD_fr:
2076 case CMD_fscx:
2077 case CMD_fscy:
2078 case CMD_fsc:
2079 case CMD_fsp:
2080 case CMD_fs:
2081 case CMD_i:
2082 case CMD_kt:
2083 case CMD_kf:
2084 case CMD_K:
2085 case CMD_ko:
2086 case CMD_k:
2087 case CMD_pbo:
2088 case CMD_p:
2089 case CMD_q:
2090 case CMD_r:
2091 case CMD_shad:
2092 case CMD_s:
2093 case CMD_an:
2094 case CMD_a:
2095 case CMD_blur:
2096 case CMD_bord:
2097 case CMD_be:
2098 case CMD_b:
2099 case CMD_u:
2100 case CMD_xbord:
2101 case CMD_xshad:
2102 case CMD_ybord:
2103 case CMD_yshad:
2104 // default:
2105 params.Add(cmd.Mid(cmd_length));
2106 break;
2107 case CMD_c:
2108 case CMD_1c :
2109 case CMD_2c :
2110 case CMD_3c :
2111 case CMD_4c :
2112 case CMD_1a :
2113 case CMD_2a :
2114 case CMD_3a :
2115 case CMD_4a :
2116 case CMD_alpha:
2117 params.Add(cmd.Mid(cmd_length).Trim(L"&H"));
2118 break;
2119 case CMD_clip:
2120 case CMD_iclip:
2121 case CMD_fade:
2122 case CMD_fad:
2123 case CMD_move:
2124 case CMD_org:
2125 case CMD_pos:
2126 break;
2127 case CMD_t:
2128 ParseSSATag(&assTag.embeded, params[params.GetCount()-1]);
2129 break;
2130 case CMD_COUNT:
2131 nUnrecognizedTags++;
2132 break;
2135 assTag.cmd = cmd;
2136 assTag.cmdType = cmd_type;
2138 nTags++;
2140 return(true);
2143 bool CRenderedTextSubtitle::ParseSSATag( CSubtitle* sub, const AssTagList& assTags, STSStyle& style, const STSStyle& org, bool fAnimate /*= false*/ )
2145 if(!sub) return(false);
2147 POSITION pos = assTags.GetHeadPosition();
2148 while(pos)
2150 const AssTag& assTag = assTags.GetNext(pos);
2151 const CStringW& cmd = assTag.cmd;
2152 AssCmdType cmd_type = assTag.cmdType;
2153 const CAtlArray<CStringW>& params = assTag.strParams;
2155 // TODO: call ParseStyleModifier(cmd, params, ..) and move the rest there
2156 const CStringW& p = params.GetCount() > 0 ? params[0] : CStringW("");
2157 switch ( cmd_type )
2159 case CMD_1c :
2160 case CMD_2c :
2161 case CMD_3c :
2162 case CMD_4c :
2164 int i = cmd[0] - L'1';
2165 DWORD c = wcstol(p, NULL, 16);
2166 style.colors[i] = !p.IsEmpty()
2167 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2168 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2169 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2170 : org.colors[i];
2171 break;
2173 case CMD_1a :
2174 case CMD_2a :
2175 case CMD_3a :
2176 case CMD_4a :
2178 int i = cmd[0] - L'1';
2179 style.alpha[i] = !p.IsEmpty()
2180 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2181 : org.alpha[i];
2182 break;
2184 case CMD_alpha:
2186 for(int i = 0; i < 4; i++)
2188 style.alpha[i] = !p.IsEmpty()
2189 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2190 : org.alpha[i];
2192 break;
2194 case CMD_an:
2196 int n = wcstol(p, NULL, 10);
2197 if(sub->m_scrAlignment < 0)
2198 sub->m_scrAlignment = (n > 0 && n < 10) ? n : org.scrAlignment;
2199 break;
2201 case CMD_a:
2203 int n = wcstol(p, NULL, 10);
2204 if(sub->m_scrAlignment < 0)
2205 sub->m_scrAlignment = (n > 0 && n < 12) ? ((((n-1)&3)+1)+((n&4)?6:0)+((n&8)?3:0)) : org.scrAlignment;
2206 break;
2208 case CMD_blur:
2210 double n = CalcAnimation(wcstod(p, NULL), style.fGaussianBlur, fAnimate);
2211 style.fGaussianBlur = !p.IsEmpty()
2212 ? (n < 0 ? 0 : n)
2213 : org.fGaussianBlur;
2214 break;
2216 case CMD_bord:
2218 double dst = wcstod(p, NULL);
2219 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2220 style.outlineWidthX = !p.IsEmpty()
2221 ? (nx < 0 ? 0 : nx)
2222 : org.outlineWidthX;
2223 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2224 style.outlineWidthY = !p.IsEmpty()
2225 ? (ny < 0 ? 0 : ny)
2226 : org.outlineWidthY;
2227 break;
2229 case CMD_be:
2231 int n = (int)(CalcAnimation(wcstol(p, NULL, 10), style.fBlur, fAnimate)+0.5);
2232 style.fBlur = !p.IsEmpty()
2234 : org.fBlur;
2235 break;
2237 case CMD_b:
2239 int n = wcstol(p, NULL, 10);
2240 style.fontWeight = !p.IsEmpty()
2241 ? (n == 0 ? FW_NORMAL : n == 1 ? FW_BOLD : n >= 100 ? n : org.fontWeight)
2242 : org.fontWeight;
2243 break;
2245 case CMD_clip:
2246 case CMD_iclip:
2248 bool invert = (cmd_type == CMD_iclip);
2249 if(params.GetCount() == 1 && !sub->m_pClipper)
2251 sub->m_pClipper = new CClipper(params[0], CSize(m_size.cx>>3, m_size.cy>>3), sub->m_scalex, sub->m_scaley, invert);
2253 else if(params.GetCount() == 2 && !sub->m_pClipper)
2255 int scale = max(wcstol(p, NULL, 10), 1);
2256 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);
2258 else if(params.GetCount() == 4)
2260 CRect r;
2261 sub->m_clipInverse = invert;
2262 r.SetRect(
2263 wcstol(params[0], NULL, 10),
2264 wcstol(params[1], NULL, 10),
2265 wcstol(params[2], NULL, 10),
2266 wcstol(params[3], NULL, 10));
2267 CPoint o(0, 0);
2268 if(sub->m_relativeTo == 1) // TODO: this should also apply to the other two clippings above
2270 o.x = m_vidrect.left>>3;
2271 o.y = m_vidrect.top>>3;
2273 sub->m_clip.SetRect(
2274 (int)CalcAnimation(sub->m_scalex*r.left + o.x, sub->m_clip.left, fAnimate),
2275 (int)CalcAnimation(sub->m_scaley*r.top + o.y, sub->m_clip.top, fAnimate),
2276 (int)CalcAnimation(sub->m_scalex*r.right + o.x, sub->m_clip.right, fAnimate),
2277 (int)CalcAnimation(sub->m_scaley*r.bottom + o.y, sub->m_clip.bottom, fAnimate));
2279 break;
2281 case CMD_c:
2283 DWORD c = wcstol(p, NULL, 16);
2284 style.colors[0] = !p.IsEmpty()
2285 ? (((int)CalcAnimation(c&0xff, style.colors[0]&0xff, fAnimate))&0xff
2286 |((int)CalcAnimation(c&0xff00, style.colors[0]&0xff00, fAnimate))&0xff00
2287 |((int)CalcAnimation(c&0xff0000, style.colors[0]&0xff0000, fAnimate))&0xff0000)
2288 : org.colors[0];
2289 break;
2291 case CMD_fade:
2292 case CMD_fad:
2294 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])
2296 if(Effect* e = new Effect)
2298 for(int i = 0; i < 3; i++)
2299 e->param[i] = wcstol(params[i], NULL, 10);
2300 for(int i = 0; i < 4; i++)
2301 e->t[i] = wcstol(params[3+i], NULL, 10);
2302 sub->m_effects[EF_FADE] = e;
2305 else if(params.GetCount() == 2 && !sub->m_effects[EF_FADE]) // {\fad(t1=t[1], t2=t[2])
2307 if(Effect* e = new Effect)
2309 e->param[0] = e->param[2] = 0xff;
2310 e->param[1] = 0x00;
2311 for(int i = 1; i < 3; i++)
2312 e->t[i] = wcstol(params[i-1], NULL, 10);
2313 e->t[0] = e->t[3] = -1; // will be substituted with "start" and "end"
2314 sub->m_effects[EF_FADE] = e;
2317 break;
2319 case CMD_fax:
2321 style.fontShiftX = !p.IsEmpty()
2322 ? CalcAnimation(wcstod(p, NULL), style.fontShiftX, fAnimate)
2323 : org.fontShiftX;
2324 break;
2326 case CMD_fay:
2328 style.fontShiftY = !p.IsEmpty()
2329 ? CalcAnimation(wcstod(p, NULL), style.fontShiftY, fAnimate)
2330 : org.fontShiftY;
2331 break;
2333 case CMD_fe:
2335 int n = wcstol(p, NULL, 10);
2336 style.charSet = !p.IsEmpty()
2338 : org.charSet;
2339 break;
2341 case CMD_fn:
2343 if(!p.IsEmpty() && p != L'0')
2344 style.fontName = CString(p).Trim();
2345 else
2346 style.fontName = org.fontName;
2347 break;
2349 case CMD_frx:
2351 style.fontAngleX = !p.IsEmpty()
2352 ? CalcAnimation(wcstod(p, NULL), style.fontAngleX, fAnimate)
2353 : org.fontAngleX;
2354 break;
2356 case CMD_fry:
2358 style.fontAngleY = !p.IsEmpty()
2359 ? CalcAnimation(wcstod(p, NULL), style.fontAngleY, fAnimate)
2360 : org.fontAngleY;
2361 break;
2363 case CMD_frz:
2364 case CMD_fr:
2366 style.fontAngleZ = !p.IsEmpty()
2367 ? CalcAnimation(wcstod(p, NULL), style.fontAngleZ, fAnimate)
2368 : org.fontAngleZ;
2369 break;
2371 case CMD_fscx:
2373 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontScaleX, fAnimate);
2374 style.fontScaleX = !p.IsEmpty()
2375 ? ((n < 0) ? 0 : n)
2376 : org.fontScaleX;
2377 break;
2379 case CMD_fscy:
2381 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontScaleY, fAnimate);
2382 style.fontScaleY = !p.IsEmpty()
2383 ? ((n < 0) ? 0 : n)
2384 : org.fontScaleY;
2385 break;
2387 case CMD_fsc:
2389 style.fontScaleX = org.fontScaleX;
2390 style.fontScaleY = org.fontScaleY;
2391 break;
2393 case CMD_fsp:
2395 style.fontSpacing = !p.IsEmpty()
2396 ? CalcAnimation(wcstod(p, NULL), style.fontSpacing, fAnimate)
2397 : org.fontSpacing;
2398 break;
2400 case CMD_fs:
2402 if(!p.IsEmpty())
2404 if(p[0] == L'-' || p[0] == L'+')
2406 double n = CalcAnimation(style.fontSize + style.fontSize*wcstol(p, NULL, 10)/10, style.fontSize, fAnimate);
2407 style.fontSize = (n > 0) ? n : org.fontSize;
2409 else
2411 double n = CalcAnimation(wcstol(p, NULL, 10), style.fontSize, fAnimate);
2412 style.fontSize = (n > 0) ? n : org.fontSize;
2415 else
2417 style.fontSize = org.fontSize;
2419 break;
2421 case CMD_i:
2423 int n = wcstol(p, NULL, 10);
2424 style.fItalic = !p.IsEmpty()
2425 ? (n == 0 ? false : n == 1 ? true : org.fItalic)
2426 : org.fItalic;
2427 break;
2429 case CMD_kt:
2431 m_kstart = !p.IsEmpty()
2432 ? wcstol(p, NULL, 10)*10
2433 : 0;
2434 m_kend = m_kstart;
2435 break;
2436 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2438 case CMD_kf:
2439 case CMD_K:
2441 m_ktype = 1;
2442 m_kstart = m_kend;
2443 m_kend += !p.IsEmpty()
2444 ? wcstol(p, NULL, 10)*10
2445 : 1000;
2446 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2447 break;
2449 case CMD_ko:
2451 m_ktype = 2;
2452 m_kstart = m_kend;
2453 m_kend += !p.IsEmpty()
2454 ? wcstol(p, NULL, 10)*10
2455 : 1000;
2456 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2457 break;
2459 case CMD_k:
2461 m_ktype = 0;
2462 m_kstart = m_kend;
2463 m_kend += !p.IsEmpty()
2464 ? wcstol(p, NULL, 10)*10
2465 : 1000;
2466 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2467 break;
2469 case CMD_move: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3][, t1=t[0], t2=t[1]])}
2471 if((params.GetCount() == 4 || params.GetCount() == 6) && !sub->m_effects[EF_MOVE])
2473 if(Effect* e = new Effect)
2475 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2476 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2477 e->param[2] = (int)(sub->m_scalex*wcstod(params[2], NULL)*8);
2478 e->param[3] = (int)(sub->m_scaley*wcstod(params[3], NULL)*8);
2479 e->t[0] = e->t[1] = -1;
2480 if(params.GetCount() == 6)
2482 for(int i = 0; i < 2; i++)
2483 e->t[i] = wcstol(params[4+i], NULL, 10);
2485 sub->m_effects[EF_MOVE] = e;
2488 break;
2490 case CMD_org: // {\org(x=param[0], y=param[1])}
2492 if(params.GetCount() == 2 && !sub->m_effects[EF_ORG])
2494 if(Effect* e = new Effect)
2496 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2497 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2498 sub->m_effects[EF_ORG] = e;
2501 break;
2503 case CMD_pbo:
2505 m_polygonBaselineOffset = wcstol(p, NULL, 10);
2506 break;
2508 case CMD_pos:
2510 if(params.GetCount() == 2 && !sub->m_effects[EF_MOVE])
2512 if(Effect* e = new Effect)
2514 e->param[0] = e->param[2] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2515 e->param[1] = e->param[3] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2516 e->t[0] = e->t[1] = 0;
2517 sub->m_effects[EF_MOVE] = e;
2520 break;
2522 case CMD_p:
2524 int n = wcstol(p, NULL, 10);
2525 m_nPolygon = (n <= 0 ? 0 : n);
2526 break;
2528 case CMD_q:
2530 int n = wcstol(p, NULL, 10);
2531 sub->m_wrapStyle = !p.IsEmpty() && (0 <= n && n <= 3)
2533 : m_defaultWrapStyle;
2534 break;
2536 case CMD_r:
2538 STSStyle* val;
2539 style = (!p.IsEmpty() && m_styles.Lookup(WToT(p), val) && val) ? *val : org;
2540 break;
2542 case CMD_shad:
2544 double dst = wcstod(p, NULL);
2545 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2546 style.shadowDepthX = !p.IsEmpty()
2547 ? (nx < 0 ? 0 : nx)
2548 : org.shadowDepthX;
2549 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2550 style.shadowDepthY = !p.IsEmpty()
2551 ? (ny < 0 ? 0 : ny)
2552 : org.shadowDepthY;
2553 break;
2555 case CMD_s:
2557 int n = wcstol(p, NULL, 10);
2558 style.fStrikeOut = !p.IsEmpty()
2559 ? (n == 0 ? false : n == 1 ? true : org.fStrikeOut)
2560 : org.fStrikeOut;
2561 break;
2563 case CMD_t: // \t([<t1>,<t2>,][<accel>,]<style modifiers>)
2565 CStringW param;
2566 m_animStart = m_animEnd = 0;
2567 m_animAccel = 1;
2568 if(params.GetCount() == 1)
2570 param = params[0];
2572 else if(params.GetCount() == 2)
2574 m_animAccel = wcstod(params[0], NULL);
2575 param = params[1];
2577 else if(params.GetCount() == 3)
2579 m_animStart = (int)wcstod(params[0], NULL);
2580 m_animEnd = (int)wcstod(params[1], NULL);
2581 param = params[2];
2583 else if(params.GetCount() == 4)
2585 m_animStart = wcstol(params[0], NULL, 10);
2586 m_animEnd = wcstol(params[1], NULL, 10);
2587 m_animAccel = wcstod(params[2], NULL);
2588 param = params[3];
2590 ParseSSATag(sub, assTag.embeded, style, org, true);
2591 sub->m_fAnimated = true;
2592 break;
2594 case CMD_u:
2596 int n = wcstol(p, NULL, 10);
2597 style.fUnderline = !p.IsEmpty()
2598 ? (n == 0 ? false : n == 1 ? true : org.fUnderline)
2599 : org.fUnderline;
2600 break;
2602 case CMD_xbord:
2604 double dst = wcstod(p, NULL);
2605 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2606 style.outlineWidthX = !p.IsEmpty()
2607 ? (nx < 0 ? 0 : nx)
2608 : org.outlineWidthX;
2609 break;
2611 case CMD_xshad:
2613 double dst = wcstod(p, NULL);
2614 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2615 style.shadowDepthX = !p.IsEmpty()
2616 ? nx
2617 : org.shadowDepthX;
2618 break;
2620 case CMD_ybord:
2622 double dst = wcstod(p, NULL);
2623 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2624 style.outlineWidthY = !p.IsEmpty()
2625 ? (ny < 0 ? 0 : ny)
2626 : org.outlineWidthY;
2627 break;
2629 case CMD_yshad:
2631 double dst = wcstod(p, NULL);
2632 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2633 style.shadowDepthY = !p.IsEmpty()
2634 ? ny
2635 : org.shadowDepthY;
2636 break;
2638 default:
2639 break;
2642 return(true);
2645 bool CRenderedTextSubtitle::ParseSSATag(CSubtitle* sub, const CStringW& str, STSStyle& style, const STSStyle& org, bool fAnimate)
2647 if(!sub) return(false);
2649 SharedPtrConstAssTagList assTags;
2650 AssTagListMruCache *ass_tag_cache = CacheManager::GetAssTagListMruCache();
2651 POSITION pos = ass_tag_cache->Lookup(str);
2652 if (pos==NULL)
2654 AssTagList *tmp = new AssTagList();
2655 ParseSSATag(tmp, str);
2656 assTags.reset(tmp);
2657 ass_tag_cache->UpdateCache(str, assTags);
2659 else
2661 assTags = ass_tag_cache->GetAt(pos);
2662 ass_tag_cache->UpdateCache( pos );
2664 return ParseSSATag(sub, *assTags, style, org, fAnimate);
2667 bool CRenderedTextSubtitle::ParseHtmlTag(CSubtitle* sub, CStringW str, STSStyle& style, STSStyle& org)
2669 if(str.Find(L"!--") == 0)
2670 return(true);
2671 bool fClosing = str[0] == L'/';
2672 str.Trim(L" /");
2673 int i = str.Find(L' ');
2674 if(i < 0) i = str.GetLength();
2675 CStringW tag = str.Left(i).MakeLower();
2676 str = str.Mid(i).Trim();
2677 CAtlArray<CStringW> attribs, params;
2678 while((i = str.Find(L'=')) > 0)
2680 attribs.Add(str.Left(i).Trim().MakeLower());
2681 str = str.Mid(i+1);
2682 for(i = 0; _istspace(str[i]); i++);
2683 str = str.Mid(i);
2684 if(str[0] == L'\"') {str = str.Mid(1); i = str.Find(L'\"');}
2685 else i = str.Find(L' ');
2686 if(i < 0) i = str.GetLength();
2687 params.Add(str.Left(i).Trim().MakeLower());
2688 str = str.Mid(i+1);
2690 if(tag == L"text")
2692 else if(tag == L"b" || tag == L"strong")
2693 style.fontWeight = !fClosing ? FW_BOLD : org.fontWeight;
2694 else if(tag == L"i" || tag == L"em")
2695 style.fItalic = !fClosing ? true : org.fItalic;
2696 else if(tag == L"u")
2697 style.fUnderline = !fClosing ? true : org.fUnderline;
2698 else if(tag == L"s" || tag == L"strike" || tag == L"del")
2699 style.fStrikeOut = !fClosing ? true : org.fStrikeOut;
2700 else if(tag == L"font")
2702 if(!fClosing)
2704 for(size_t i = 0; i < attribs.GetCount(); i++)
2706 if(params[i].IsEmpty()) continue;
2707 int nColor = -1;
2708 if(attribs[i] == L"face")
2710 style.fontName = params[i];
2712 else if(attribs[i] == L"size")
2714 if(params[i][0] == L'+')
2715 style.fontSize += wcstol(params[i], NULL, 10);
2716 else if(params[i][0] == L'-')
2717 style.fontSize -= wcstol(params[i], NULL, 10);
2718 else
2719 style.fontSize = wcstol(params[i], NULL, 10);
2721 else if(attribs[i] == L"color")
2723 nColor = 0;
2725 else if(attribs[i] == L"outline-color")
2727 nColor = 2;
2729 else if(attribs[i] == L"outline-level")
2731 style.outlineWidthX = style.outlineWidthY = wcstol(params[i], NULL, 10);
2733 else if(attribs[i] == L"shadow-color")
2735 nColor = 3;
2737 else if(attribs[i] == L"shadow-level")
2739 style.shadowDepthX = style.shadowDepthY = wcstol(params[i], NULL, 10);
2741 if(nColor >= 0 && nColor < 4)
2743 CString key = WToT(params[i]).TrimLeft(L'#');
2744 DWORD val;
2745 if(g_colors.Lookup(key, val))
2746 style.colors[nColor] = val;
2747 else if((style.colors[nColor] = _tcstol(key, NULL, 16)) == 0)
2748 style.colors[nColor] = 0x00ffffff; // default is white
2749 style.colors[nColor] = ((style.colors[nColor]>>16)&0xff)|((style.colors[nColor]&0xff)<<16)|(style.colors[nColor]&0x00ff00);
2753 else
2755 style.fontName = org.fontName;
2756 style.fontSize = org.fontSize;
2757 memcpy(style.colors, org.colors, sizeof(style.colors));
2760 else if(tag == L"k" && attribs.GetCount() == 1 && attribs[0] == L"t")
2762 m_ktype = 1;
2763 m_kstart = m_kend;
2764 m_kend += wcstol(params[0], NULL, 10);
2766 else
2767 return(false);
2768 return(true);
2771 double CRenderedTextSubtitle::CalcAnimation(double dst, double src, bool fAnimate)
2773 int s = m_animStart ? m_animStart : 0;
2774 int e = m_animEnd ? m_animEnd : m_delay;
2775 if(fabs(dst-src) >= 0.0001 && fAnimate)
2777 if(m_time < s) dst = src;
2778 else if(s <= m_time && m_time < e)
2780 double t = pow(1.0 * (m_time - s) / (e - s), m_animAccel);
2781 dst = (1 - t) * src + t * dst;
2783 // else dst = dst;
2785 return(dst);
2788 CSubtitle* CRenderedTextSubtitle::GetSubtitle(int entry)
2790 CSubtitle* sub;
2791 if(m_subtitleCache.Lookup(entry, sub))
2793 if(sub->m_fAnimated) {delete sub; sub = NULL;}
2794 else return(sub);
2796 sub = new CSubtitle();
2797 if(!sub) return(NULL);
2798 CStringW str = GetStrW(entry, true);
2799 STSStyle stss, orgstss;
2800 GetStyle(entry, &stss);
2801 if (stss.fontScaleX == stss.fontScaleY && m_dPARCompensation != 1.0)
2803 switch(m_ePARCompensationType)
2805 case EPCTUpscale:
2806 if (m_dPARCompensation < 1.0)
2807 stss.fontScaleY /= m_dPARCompensation;
2808 else
2809 stss.fontScaleX *= m_dPARCompensation;
2810 break;
2811 case EPCTDownscale:
2812 if (m_dPARCompensation < 1.0)
2813 stss.fontScaleX *= m_dPARCompensation;
2814 else
2815 stss.fontScaleY /= m_dPARCompensation;
2816 break;
2817 case EPCTAccurateSize:
2818 stss.fontScaleX *= m_dPARCompensation;
2819 break;
2822 orgstss = stss;
2823 sub->m_clip.SetRect(0, 0, m_size.cx>>3, m_size.cy>>3);
2824 sub->m_scrAlignment = -stss.scrAlignment;
2825 sub->m_wrapStyle = m_defaultWrapStyle;
2826 sub->m_fAnimated = false;
2827 sub->m_relativeTo = stss.relativeTo;
2828 sub->m_scalex = m_dstScreenSize.cx > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Width() : m_size.cx) / (m_dstScreenSize.cx*8) : 1.0;
2829 sub->m_scaley = m_dstScreenSize.cy > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Height() : m_size.cy) / (m_dstScreenSize.cy*8) : 1.0;
2830 m_animStart = m_animEnd = 0;
2831 m_animAccel = 1;
2832 m_ktype = m_kstart = m_kend = 0;
2833 m_nPolygon = 0;
2834 m_polygonBaselineOffset = 0;
2835 ParseEffect(sub, m_entries.GetAt(entry).effect);
2836 while(!str.IsEmpty())
2838 bool fParsed = false;
2839 int i;
2840 if(str[0] == L'{' && (i = str.Find(L'}')) > 0)
2842 if(fParsed = ParseSSATag(sub, str.Mid(1, i-1), stss, orgstss))
2843 str = str.Mid(i+1);
2845 else if(str[0] == L'<' && (i = str.Find(L'>')) > 0)
2847 if(fParsed = ParseHtmlTag(sub, str.Mid(1, i-1), stss, orgstss))
2848 str = str.Mid(i+1);
2850 if(fParsed)
2852 i = str.FindOneOf(L"{<");
2853 if(i < 0) i = str.GetLength();
2854 if(i == 0) continue;
2856 else
2858 i = str.Mid(1).FindOneOf(L"{<");
2859 if(i < 0) i = str.GetLength()-1;
2860 i++;
2862 STSStyle tmp = stss;
2863 tmp.fontSize = sub->m_scaley*tmp.fontSize*64;
2864 tmp.fontSpacing = sub->m_scalex*tmp.fontSpacing*64;
2865 tmp.outlineWidthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2866 tmp.outlineWidthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2867 tmp.shadowDepthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2868 tmp.shadowDepthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2869 FwSTSStyle fw_tmp(tmp);
2870 if(m_nPolygon)
2872 ParsePolygon(sub, str.Left(i), fw_tmp);
2874 else
2876 ParseString(sub, str.Left(i), fw_tmp);
2878 str = str.Mid(i);
2880 sub->m_fAnimated2 |= sub->m_fAnimated;
2881 if( sub->m_effects[EF_FADE] || sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL]
2882 || sub->m_effects[EF_MOVE] )
2883 sub->m_fAnimated2 = true;
2884 // just a "work-around" solution... in most cases nobody will want to use \org together with moving but without rotating the subs
2885 if(sub->m_effects[EF_ORG] && (sub->m_effects[EF_MOVE] || sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL]))
2886 sub->m_fAnimated = true;
2887 sub->m_scrAlignment = abs(sub->m_scrAlignment);
2888 STSEntry stse = m_entries.GetAt(entry);
2889 CRect marginRect = stse.marginRect;
2890 if(marginRect.left == 0) marginRect.left = orgstss.marginRect.get().left;
2891 if(marginRect.top == 0) marginRect.top = orgstss.marginRect.get().top;
2892 if(marginRect.right == 0) marginRect.right = orgstss.marginRect.get().right;
2893 if(marginRect.bottom == 0) marginRect.bottom = orgstss.marginRect.get().bottom;
2894 marginRect.left = (int)(sub->m_scalex*marginRect.left*8);
2895 marginRect.top = (int)(sub->m_scaley*marginRect.top*8);
2896 marginRect.right = (int)(sub->m_scalex*marginRect.right*8);
2897 marginRect.bottom = (int)(sub->m_scaley*marginRect.bottom*8);
2898 if(stss.relativeTo == 1)
2900 marginRect.left += m_vidrect.left;
2901 marginRect.top += m_vidrect.top;
2902 marginRect.right += m_size.cx - m_vidrect.right;
2903 marginRect.bottom += m_size.cy - m_vidrect.bottom;
2905 sub->CreateClippers(m_size);
2906 sub->MakeLines(m_size, marginRect);
2907 m_subtitleCache[entry] = sub;
2908 return(sub);
2913 STDMETHODIMP CRenderedTextSubtitle::NonDelegatingQueryInterface(REFIID riid, void** ppv)
2915 CheckPointer(ppv, E_POINTER);
2916 *ppv = NULL;
2917 return
2918 QI(IPersist)
2919 QI(ISubStream)
2920 QI(ISubPicProvider)
2921 QI(ISubPicProviderEx)
2922 __super::NonDelegatingQueryInterface(riid, ppv);
2925 // ISubPicProvider
2927 STDMETHODIMP_(POSITION) CRenderedTextSubtitle::GetStartPosition(REFERENCE_TIME rt, double fps)
2929 //DbgLog((LOG_TRACE, 3, "rt:%lu", (ULONG)rt/10000));
2930 m_fps = fps;//fix me: check is fps changed and do some re-init thing
2931 int iSegment;
2932 int subIndex = 1;//If a segment has animate effect then it corresponds to several subpics.
2933 //subIndex, 1 based, indicates which subpic the result corresponds to.
2934 rt /= 10000i64;
2935 const STSSegment *stss = SearchSubs((int)rt, fps, &iSegment, NULL);
2936 if(stss==NULL)
2937 return NULL;
2938 else if(stss->animated)
2940 int start = TranslateSegmentStart(iSegment, fps);
2941 if(rt > start)
2942 subIndex = (rt-start)/RTS_ANIMATE_SUBPIC_DUR + 1;
2944 //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));
2945 return (POSITION)(subIndex | (iSegment<<RTS_POS_SEGMENT_INDEX_BITS));
2946 //if(iSegment < 0) iSegment = 0;
2947 //return(GetNext((POSITION)iSegment));
2950 STDMETHODIMP_(POSITION) CRenderedTextSubtitle::GetNext(POSITION pos)
2952 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2953 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2954 const STSSegment *stss = GetSegment(iSegment);
2955 ASSERT(stss!=NULL && stss->subs.GetCount()>0);
2956 //DbgLog((LOG_TRACE, 3, "stss:%x count:%d", stss, stss->subs.GetCount()));
2957 if(!stss->animated)
2959 iSegment++;
2960 subIndex = 1;
2962 else
2964 int start, end;
2965 TranslateSegmentStartEnd(iSegment, m_fps, start, end);
2966 if(start+RTS_ANIMATE_SUBPIC_DUR*subIndex < end)
2967 subIndex++;
2968 else
2970 iSegment++;
2971 subIndex = 1;
2974 if(GetSegment(iSegment) != NULL)
2976 ASSERT(GetSegment(iSegment)->subs.GetCount()>0);
2977 return (POSITION)(subIndex | (iSegment<<RTS_POS_SEGMENT_INDEX_BITS));
2979 else
2980 return NULL;
2983 //@return: <0 if segment not found
2984 STDMETHODIMP_(REFERENCE_TIME) CRenderedTextSubtitle::GetStart(POSITION pos, double fps)
2986 //return(10000i64 * TranslateSegmentStart((int)pos-1, fps));
2987 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
2988 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
2989 int start = TranslateSegmentStart(iSegment, fps);
2990 const STSSegment *stss = GetSegment(iSegment);
2991 if(stss!=NULL)
2993 return (start + (subIndex-1)*RTS_ANIMATE_SUBPIC_DUR)*10000i64;
2995 else
2997 return -1;
3001 //@return: <0 if segment not found
3002 STDMETHODIMP_(REFERENCE_TIME) CRenderedTextSubtitle::GetStop(POSITION pos, double fps)
3004 // return(10000i64 * TranslateSegmentEnd((int)pos-1, fps));
3005 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3006 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
3007 int start, end, ret;
3008 TranslateSegmentStartEnd(iSegment, fps, start, end);
3009 const STSSegment *stss = GetSegment(iSegment);
3010 if(stss!=NULL)
3012 if(!stss->animated)
3013 ret = end;
3014 else
3016 ret = start+subIndex*RTS_ANIMATE_SUBPIC_DUR;
3017 if(ret > end)
3018 ret = end;
3020 return ret*10000i64;
3022 else
3023 return -1;
3026 //@start, @stop: -1 if segment not found; @stop may < @start if subIndex exceed uppper bound
3027 STDMETHODIMP_(VOID) CRenderedTextSubtitle::GetStartStop(POSITION pos, double fps, /*out*/REFERENCE_TIME &start, /*out*/REFERENCE_TIME &stop)
3029 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3030 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
3031 int tempStart, tempEnd;
3032 TranslateSegmentStartEnd(iSegment, fps, tempStart, tempEnd);
3033 start = tempStart;
3034 stop = tempEnd;
3035 const STSSegment *stss = GetSegment(iSegment);
3036 if(stss!=NULL)
3038 if(stss->animated)
3040 start += (subIndex-1)*RTS_ANIMATE_SUBPIC_DUR;
3041 if(start+RTS_ANIMATE_SUBPIC_DUR < stop)
3042 stop = start+RTS_ANIMATE_SUBPIC_DUR;
3044 //DbgLog((LOG_TRACE, 3, "animated:%d seg:%d idx:%d start:%d stop:%lu", stss->animated, iSegment, subIndex, (ULONG)start, (ULONG)stop));
3045 start *= 10000i64;
3046 stop *= 10000i64;
3048 else
3050 start = -1;
3051 stop = -1;
3055 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsAnimated(POSITION pos)
3057 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3058 if(iSegment>=0 && iSegment<m_segments.GetCount())
3059 return m_segments[iSegment].animated;
3060 else
3061 return false;
3062 //return(true);
3065 struct LSub {int idx, layer, readorder;};
3067 static int lscomp(const void* ls1, const void* ls2)
3069 int ret = ((LSub*)ls1)->layer - ((LSub*)ls2)->layer;
3070 if(!ret) ret = ((LSub*)ls1)->readorder - ((LSub*)ls2)->readorder;
3071 return(ret);
3074 STDMETHODIMP CRenderedTextSubtitle::RenderEx(SubPicDesc& spd, REFERENCE_TIME rt, double fps, CAtlList<CRect>& rectList)
3076 CRect bbox2(0,0,0,0);
3077 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))
3078 Init(CSize(spd.w, spd.h), spd.vidrect);
3079 int t = (int)(rt / 10000);
3080 int segment;
3081 //const
3082 STSSegment* stss = SearchSubs2(t, fps, &segment);
3083 if(!stss) return S_FALSE;
3084 // clear any cached subs not in the range of +/-30secs measured from the segment's bounds
3086 POSITION pos = m_subtitleCache.GetStartPosition();
3087 while(pos)
3089 int key;
3090 CSubtitle* value;
3091 m_subtitleCache.GetNextAssoc(pos, key, value);
3092 STSEntry& stse = m_entries.GetAt(key);
3093 if(stse.end <= (t-30000) || stse.start > (t+30000))
3095 delete value;
3096 m_subtitleCache.RemoveKey(key);
3097 pos = m_subtitleCache.GetStartPosition();
3101 m_sla.AdvanceToSegment(segment, stss->subs);
3102 CAtlArray<LSub> subs;
3103 for(int i = 0, j = stss->subs.GetCount(); i < j; i++)
3105 LSub ls;
3106 ls.idx = stss->subs[i];
3107 ls.layer = m_entries.GetAt(stss->subs[i]).layer;
3108 ls.readorder = m_entries.GetAt(stss->subs[i]).readorder;
3109 subs.Add(ls);
3111 qsort(subs.GetData(), subs.GetCount(), sizeof(LSub), lscomp);
3113 CompositeDrawItemList drawItemList;
3114 for(int i = 0, j = subs.GetCount(); i < j; i++)
3116 int entry = subs[i].idx;
3117 STSEntry stse = m_entries.GetAt(entry);
3119 int start = TranslateStart(entry, fps);
3120 m_time = t - start;
3121 m_delay = TranslateEnd(entry, fps) - start;
3123 CSubtitle* s = GetSubtitle(entry);
3124 if(!s) continue;
3125 stss->animated |= s->m_fAnimated2;
3126 CRect clipRect = s->m_clip;
3127 CRect r = s->m_rect;
3128 CSize spaceNeeded = r.Size();
3129 // apply the effects
3130 bool fPosOverride = false, fOrgOverride = false;
3131 int alpha = 0x00;
3132 CPoint org2;
3133 for(int k = 0; k < EF_NUMBEROFEFFECTS; k++)
3135 if(!s->m_effects[k]) continue;
3136 switch(k)
3138 case EF_MOVE: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3], t1=t[0], t2=t[1])}
3140 CPoint p;
3141 CPoint p1(s->m_effects[k]->param[0], s->m_effects[k]->param[1]);
3142 CPoint p2(s->m_effects[k]->param[2], s->m_effects[k]->param[3]);
3143 int t1 = s->m_effects[k]->t[0];
3144 int t2 = s->m_effects[k]->t[1];
3145 if(t2 < t1) {int t = t1; t1 = t2; t2 = t;}
3146 if(t1 <= 0 && t2 <= 0) {t1 = 0; t2 = m_delay;}
3147 if(m_time <= t1) p = p1;
3148 else if (p1 == p2) p = p1;
3149 else if(t1 < m_time && m_time < t2)
3151 double t = 1.0*(m_time-t1)/(t2-t1);
3152 p.x = (int)((1-t)*p1.x + t*p2.x);
3153 p.y = (int)((1-t)*p1.y + t*p2.y);
3155 else p = p2;
3156 r = CRect(
3157 CPoint((s->m_scrAlignment%3) == 1 ? p.x : (s->m_scrAlignment%3) == 0 ? p.x - spaceNeeded.cx : p.x - (spaceNeeded.cx+1)/2,
3158 s->m_scrAlignment <= 3 ? p.y - spaceNeeded.cy : s->m_scrAlignment <= 6 ? p.y - (spaceNeeded.cy+1)/2 : p.y),
3159 spaceNeeded);
3160 if(s->m_relativeTo == 1)
3161 r.OffsetRect(m_vidrect.TopLeft());
3162 fPosOverride = true;
3164 break;
3165 case EF_ORG: // {\org(x=param[0], y=param[1])}
3167 org2 = CPoint(s->m_effects[k]->param[0], s->m_effects[k]->param[1]);
3168 fOrgOverride = true;
3170 break;
3171 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])
3173 int t1 = s->m_effects[k]->t[0];
3174 int t2 = s->m_effects[k]->t[1];
3175 int t3 = s->m_effects[k]->t[2];
3176 int t4 = s->m_effects[k]->t[3];
3177 if(t1 == -1 && t4 == -1) {t1 = 0; t3 = m_delay-t3; t4 = m_delay;}
3178 if(m_time < t1) alpha = s->m_effects[k]->param[0];
3179 else if(m_time >= t1 && m_time < t2)
3181 double t = 1.0 * (m_time - t1) / (t2 - t1);
3182 alpha = (int)(s->m_effects[k]->param[0]*(1-t) + s->m_effects[k]->param[1]*t);
3184 else if(m_time >= t2 && m_time < t3) alpha = s->m_effects[k]->param[1];
3185 else if(m_time >= t3 && m_time < t4)
3187 double t = 1.0 * (m_time - t3) / (t4 - t3);
3188 alpha = (int)(s->m_effects[k]->param[1]*(1-t) + s->m_effects[k]->param[2]*t);
3190 else if(m_time >= t4) alpha = s->m_effects[k]->param[2];
3192 break;
3193 case EF_BANNER: // Banner;delay=param[0][;leftoright=param[1];fadeawaywidth=param[2]]
3195 int left = s->m_relativeTo == 1 ? m_vidrect.left : 0,
3196 right = s->m_relativeTo == 1 ? m_vidrect.right : m_size.cx;
3197 r.left = !!s->m_effects[k]->param[1]
3198 ? (left/*marginRect.left*/ - spaceNeeded.cx) + (int)(m_time*8.0/s->m_effects[k]->param[0])
3199 : (right /*- marginRect.right*/) - (int)(m_time*8.0/s->m_effects[k]->param[0]);
3200 r.right = r.left + spaceNeeded.cx;
3201 clipRect &= CRect(left>>3, clipRect.top, right>>3, clipRect.bottom);
3202 fPosOverride = true;
3204 break;
3205 case EF_SCROLL: // Scroll up/down(toptobottom=param[3]);top=param[0];bottom=param[1];delay=param[2][;fadeawayheight=param[4]]
3207 r.top = !!s->m_effects[k]->param[3]
3208 ? s->m_effects[k]->param[0] + (int)(m_time*8.0/s->m_effects[k]->param[2]) - spaceNeeded.cy
3209 : s->m_effects[k]->param[1] - (int)(m_time*8.0/s->m_effects[k]->param[2]);
3210 r.bottom = r.top + spaceNeeded.cy;
3211 CRect cr(0, (s->m_effects[k]->param[0] + 4) >> 3, spd.w, (s->m_effects[k]->param[1] + 4) >> 3);
3212 if(s->m_relativeTo == 1)
3213 r.top += m_vidrect.top,
3214 r.bottom += m_vidrect.top,
3215 cr.top += m_vidrect.top>>3,
3216 cr.bottom += m_vidrect.top>>3;
3217 clipRect &= cr;
3218 fPosOverride = true;
3220 break;
3221 default:
3222 break;
3225 if(!fPosOverride && !fOrgOverride && !s->m_fAnimated)
3226 r = m_sla.AllocRect(s, segment, entry, stse.layer, m_collisions);
3227 CPoint org;
3228 org.x = (s->m_scrAlignment%3) == 1 ? r.left : (s->m_scrAlignment%3) == 2 ? r.CenterPoint().x : r.right;
3229 org.y = s->m_scrAlignment <= 3 ? r.bottom : s->m_scrAlignment <= 6 ? r.CenterPoint().y : r.top;
3230 if(!fOrgOverride) org2 = org;
3231 SharedArrayByte pAlphaMask;
3232 if( s->m_pClipper )
3233 pAlphaMask = s->m_pClipper->m_pAlphaMask;
3234 CPoint p, p2(0, r.top);
3235 POSITION pos;
3236 p = p2;
3237 // Rectangles for inverse clip
3238 CRect iclipRect[4];
3239 iclipRect[0] = CRect(0, 0, spd.w, clipRect.top);
3240 iclipRect[1] = CRect(0, clipRect.top, clipRect.left, clipRect.bottom);
3241 iclipRect[2] = CRect(clipRect.right, clipRect.top, spd.w, clipRect.bottom);
3242 iclipRect[3] = CRect(0, clipRect.bottom, spd.w, spd.h);
3243 int dbgTest = 0;
3244 bbox2 = CRect(0,0,0,0);
3245 pos = s->GetHeadLinePosition();
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);
3277 drawItemList.AddTailList(&tmpDrawItemList);
3278 p.y += l->m_ascent + l->m_descent;
3280 rectList.AddTail(bbox2);
3283 Draw(spd, drawItemList);
3284 return (subs.GetCount() && !rectList.IsEmpty()) ? S_OK : S_FALSE;
3288 STDMETHODIMP CRenderedTextSubtitle::Render(SubPicDesc& spd, REFERENCE_TIME rt, double fps, RECT& bbox)
3290 CAtlList<CRect> rectList;
3291 HRESULT result = RenderEx(spd, rt, fps, rectList);
3292 POSITION pos = rectList.GetHeadPosition();
3293 CRect bbox2(0,0,0,0);
3294 while(pos!=NULL)
3296 bbox2 |= rectList.GetNext(pos);
3298 bbox = bbox2;
3299 return result;
3302 // IPersist
3304 STDMETHODIMP CRenderedTextSubtitle::GetClassID(CLSID* pClassID)
3306 return pClassID ? *pClassID = __uuidof(this), S_OK : E_POINTER;
3309 // ISubStream
3311 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStreamCount()
3313 return(1);
3316 STDMETHODIMP CRenderedTextSubtitle::GetStreamInfo(int iStream, WCHAR** ppName, LCID* pLCID)
3318 if(iStream != 0) return E_INVALIDARG;
3319 if(ppName)
3321 if(!(*ppName = (WCHAR*)CoTaskMemAlloc((m_name.GetLength()+1)*sizeof(WCHAR))))
3322 return E_OUTOFMEMORY;
3323 wcscpy(*ppName, CStringW(m_name));
3325 if(pLCID)
3327 *pLCID = 0; // TODO
3329 return S_OK;
3332 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStream()
3334 return(0);
3337 STDMETHODIMP CRenderedTextSubtitle::SetStream(int iStream)
3339 return iStream == 0 ? S_OK : E_FAIL;
3342 STDMETHODIMP CRenderedTextSubtitle::Reload()
3344 CFileStatus s;
3345 if(!CFile::GetStatus(m_path, s)) return E_FAIL;
3346 return !m_path.IsEmpty() && Open(m_path, DEFAULT_CHARSET) ? S_OK : E_FAIL;
3349 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsColorTypeSupported( int type )
3351 return type==MSP_AY11 ||
3352 type==MSP_AYUV ||
3353 type==MSP_AUYV ||
3354 type==MSP_RGBA;
3357 void CRenderedTextSubtitle::Draw( SubPicDesc& spd, CompositeDrawItemList& drawItemList )
3359 POSITION pos = drawItemList.GetHeadPosition();
3360 while(pos)
3362 CompositeDrawItem& draw_item = drawItemList.GetNext(pos);
3363 if(draw_item.shadow)
3364 Rasterizer::Draw( spd, *draw_item.shadow );
3366 pos = drawItemList.GetHeadPosition();
3367 while(pos)
3369 CompositeDrawItem& draw_item = drawItemList.GetNext(pos);
3370 if(draw_item.outline)
3371 Rasterizer::Draw( spd, *draw_item.outline );
3373 pos = drawItemList.GetHeadPosition();
3374 while(pos)
3376 CompositeDrawItem& draw_item = drawItemList.GetNext(pos);
3377 if(draw_item.body)
3378 Rasterizer::Draw( spd, *draw_item.body );